Android some tool class rollup _android

Source: Internet
Author: User
Tags md5

A Paint, Canvas

public class Drawview extends view{
  private Paint paint1;
  Public Drawview (Context Context,attributeset set) {
    super (Context,set);
  }
     
  public void OnDraw (Canvas Canvas) {
    
    super.ondraw (Canvas);
        New A Brush object
    paint1= new Paint ();
    Canvas.drawcolor (color.transparent);
    Sets the property
    Paint1.setantialias (True) for the brush;
    Paint1.setcolor (Color.gray);
    Paint1.setstyle (Paint.Style.FILL);
    Paint1.setstrokewidth (3);
 
    Draw a round
    //canvas.drawcircle (arg0, Arg1, arg2, arg3);
    Canvas.drawcircle (5, paint1);
    }

Two Asyncimagetask

  * *///The default number of threads opened is 128 if more than 128 will be placed in queue for queuing//inheriting asynctask, specify three parameters the first is the type of the parameter to be passed the second is the parameter type of the progress the third is the parameter type of the return result (//when calling Execut E executes the PreExecute first and then executes to enable the thread pool execute//Then initiates the child thread to perform the doinbackground--the asynctask inside will have handler to return the result to the UI thread/ This method of OnPostExecute is then updated on the UI interface/private void Asyncimageload (ImageView imageview, String path) {Asyncimag
      ETask Asyncimagetask = new Asyncimagetask (ImageView);
      
    Asyncimagetask.execute (path);
    Private Final class Asyncimagetask extends Asynctask<string, Integer, uri>{private ImageView ImageView;
     
    Public Asyncimagetask (ImageView imageview) {this.imageview = ImageView; The try {uri uu = contactservice.getimage (param) executed in protected Uri doinbackground (String ... params) {//child thread
        S[0], cache);//The URI path is thrown to the main thread System.out.println (uu+ "zuuuuuuuu");
      return to UU;
      catch (Exception e) {e.printstacktrace ();
    return null; } protected void OnpostExecute (Uri result) {///run on the main thread, get the Uri path, make the picture update log.i ("Test", result+ ""); 
 if (result!=null && imageview!= null) Imageview.setimageuri (Result)//setimageuri This method loads the picture according to the path}

Triple intercept string

Intercepts a string from 0 to the first "/" character
 string name = Result.substring (0,result.indexof ("/"));
Intercepts a string from the first character "/" to the Last "/" character
 string name = Result.substring (Result.indexof ("/") +1, Result.lastindexof ("/")));


Four MD5 is widely used for encryption

Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;
public class MD5 {public
  static string getMD5 (string content) {
    try {
      MessageDigest digest = messagedigest.ge Tinstance ("MD5");
      Digest.update (Content.getbytes ());
      Return Gethashstring (Digest);
      
    } catch (NoSuchAlgorithmException e) {
      e.printstacktrace ();
    }
    return null;
  }
  
  private static String gethashstring (MessageDigest Digest) {
    StringBuilder builder = new StringBuilder ();
    For (Byte b:digest.digest ()) {
      builder.append (integer.tohexstring (b >> 4) & 0xf));
      Builder.append (integer.tohexstring (b & 0xf));
    }
    return builder.tostring ();
  }

Five bytes in the read stream:

Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
public class Streamtool {
  /**
   * Read the data in the stream
   * @param instream *
   @return *
   @throws
   Exception
  * * public static byte[] Read (InputStream instream) throws exception{bytearrayoutputstream
    = new Bytearrayoutputstream ();
    byte[] buffer = new byte[1024];
    int len = 0;
    while (len = instream.read (buffer))!=-1) {
      outstream.write (buffer, 0, Len);
    }
    Instream.close ();
    return Outstream.tobytearray ();
  }

XML data stream from the six-resolution server


   * * Get the Contact list set after parsing XML
  /public static list<contact> Getcontacts () throws Exception {
    
    St Ring path = Stringtools.geturl_list_xml;
    URL url = new URL (path);
  URLConnection and HttpURLConnection are abstract classes and cannot instantiate objects directly.
  //Its objects are obtained mainly through the OpenConnection method of the URL.
  //Use HttpURLConnection object to get Web page data
    from the network HttpURLConnection con = (httpurlconnection) url.openconnection ();
    Con.setreadtimeout (5000);
    Con.setrequestmethod ("get");
    if (con.getresponsecode () = =) {//http protocol, which has the corresponding status code explanation, 
                   //Here is said to judge whether the normal response request data.
      Return Parsexml (Con.getinputstream ()); FFF
      //return Streamtool.read (Con.getinputstream ());
    }
    return null;
  }

of which Parsexml (Con.getinputstream ());

  /* Parse XML/private static list<contact> Parsexml (InputStream xml) throws Exception {List<con
    tact> contacts = new arraylist<contact> ();
    Contact contact = NULL;
    Xmlpullparser Pullparser = Xml.newpullparser ();
    Pullparser.setinput (XML, "UTF-8");
    int event = Pullparser.geteventtype (); while (event!= xmlpullparser.end_document) {switch (event) {case XmlPullParser.START_TAG:if ("Contac
          T ". Equals (Pullparser.getname ())) {contact = new contacts ();
        Contact.id = new Integer (pullparser.getattributevalue (0)); }else if ("Name". Equals (Pullparser.getname ())) {contact.name = Pullparser.nexttext (); Nexttext is not. getText!!
        !! }else if ("image". Equals (Pullparser.getname ()) {Contact.imageurl = Pullparser.getattributevalue (0);
      FFF} break; Case XmlPullParser.END_TAG:if ("Contacts". Equals (Pullparser.getname ())) {Contacts. Add (Contact);
        contact = NULL;
      } break;
    event = Pullparser.next ();
  return contacts; 
 }

Seven parse the Json data passed by the server:

/* Parse Json Data/private static list<secondactivity_goods_bean> Parsejso N (InputStream inputstream) throws Exception {list<secondactivity_goods_bean> Secondactivity_goods_beans =
    New Arraylist<secondactivity_goods_bean> ();
    Secondactivity_goods_bean Goodbean = null;
    byte[] data = Streamtool.read (InputStream);
    String json = new string (data);
    Jsonarray array = new Jsonarray (JSON);
      for (int i=0;i<array.length (); i++) {Jsonobject jsonobject = Array.getjsonobject (i);
      Jsonobject.getstring ("ImageUrl");
      Jsonobject.getstring ("Imagecontent");
      Jsonobject.getstring ("Goodsprice"); Goodbean = new Secondactivity_goods_bean (jsonobject.getstring ("ImageUrl"), jsonobject.getstring
      ("Imagecontent"), Jsonobject.getstring ("Goodsprice"));
    Secondactivity_goods_beans.add (Goodbean);
  return null; }

Eight submitting data to the server:

  private static string Sendpostrequest (String path,map<string, string> parame, String encoding) throws Exceptio  n {//stringbuilder to be combined into this data sent to the server Telephone_number=telephone_number&password=password StringBuilder
    New StringBuilder ();
        if (parame!= null &&!parame.isempty ()) {for (map.entry<string, string> entry:parame.entrySet ()) {
        Data.append (Entry.getkey ()). Append ("=");
        Data.append (Urlencoder.encode (Entry.getvalue (), encoding));
      Data.append ("&"); } Data.deletecharat (Data.length ()-1);//The end will be more "&"} byte[] entity = data.tostring (). GetBytes ();//Default Get UTF
    -8 byte code HttpURLConnection conn = (httpurlconnection) new URL (path). OpenConnection ();
    Conn.setconnecttimeout (5000); Conn.setrequestmethod ("POST"); Send the request Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded") to the server by post; Set the header field of the POST request Co Nn.setrequestproperty ("Content-length", String.valueof (EntiTy.length)//Set the POST Request header field OutputStream OutStream = Conn.getoutputstream ()//Get Data output stream Outstream.write (entity) //The data to the HTTP output stream buffer if (conn.getresponsecode () = = 200) {//The Android client requests the request code when the data output stream buffer to the server//strin G S = conn.getresponsemessage ()///This method gets the string "OK" * * to get the data returned by the server!!!
      Get the return value of the server can determine whether the data upload success/byte[] StringData = Streamtool.read (Conn.getinputstream ());
      String stringflag = new String (StringData, "UTF-8"); return stringflag;
  Data sent successfully returns true} return "Submit_fail";
 }

Nine sharedpreferences

public class Sharedpreferences_service {private context context;
  Private Sharedpreferences sp;
  Public Sharedpreferences_service (Context Applicationcon) {this.context = Applicationcon; /** * The file is stored in the data/data/corresponding package name/rsgistered_form.xml under File Explorer to export the file * @param name * @param Telephone_numbe R * @param password */public void setparament (String name,string telephone_number,string password) {SP = cont Ext.getsharedpreferences ("Rsgistered_form", context.
    Mode_append);
    Editor et = Sp.edit ();
    Et.putstring ("name", name);
    Et.putstring ("Telephone_number", Telephone_number);
    Et.putstring ("password", password);
  Et.commit (); /** * data/data/the corresponding rsgistered_form.xml in folder File Explorer * @return * * Public map<string, String&gt ;
    Getparament () {map<string, string> parmes = new hashmap<string, string> (); SP = context.getsharedpreferences ("Rsgistered_form", context.
    Mode_append); Parmes.put ("name", sp.)GetString ("name", ""))//Gets the name field, the argument is empty and returns an empty Parmes.put ("Telephone_number", Sp.getstring ("Telephone_number", ""));
    Parmes.put ("Password", sp.getstring ("Password", ""));
  return parmes;
 }
}

10 <!--set fillet radius--><!--gradient;

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android= "Http://schemas.android.com/apk/res/android"
    Android:shape= "Rectangle" > <!--rounded corner--> <corners android:radius= "9DP" android:topleftradius= "2DP" android:toprightradius= "2DP" android:bottomleftradius= "2DP" android:bottomrightradius= "2DP"/> <!--set fillet radius --><!--gradient--> <gradient android:startcolor= "@android: Color/white" android:centercolor= "@android: Color /black "android:endcolor=" @android: Color/black "android:uselevel=" true "android:angle=" "Android:type=" R
    Adial "android:centerx=" 0 "android:centery=" 0 "android:gradientradius=" "/> <!--interval--> <padding android:left= "2DP" android:top= "2DP" android:right= "2DP" android:bottom= "2DP"/> <!--intervals in all directions--&GT;&L t;! --Size--> <size android:width= "50DP" android:height= "50DP"/> <!--width and height--><!--fill--> <so Lid android:color= "@aNdroid:color/white "/> <!--fill color--><!--stroke--> <stroke android:width=" 2DP "android:color=" @andr
 Oid:color/black "android:dashwidth=" 1DP "android:dashgap=" 2DP "/> </shape>

You can also use selector in the definition of a xxx.xml under the Drawable folder

<?xml version= "1.0" encoding= "Utf-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android >
 <item android:drawable= "@drawable/button_pressed_bg" android:state_pressed= "true" ></ item>
 <item android:drawable= "@drawable/shape_image" ></item>
</selector>

Defines a rectangular background with four angular radians

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android " 
  android:shape=" Rectangle >
  <!--Specify 4 corners of radians-->
  <corners android:topleftradius= "2px "
    android:toprightradius=" 2px "
    android:bottomleftradius=" 2px "
    android:bottomrightradius=" 2px "/>
  <!--specify background color-->
  <solid android:color= "#FFFFFF"/>
  <!--Specify the color width of the frame-->
  < Stroke android:width= "0.5DP" android:color= "#7A7A7A"/>
  
</shape>

11 Anim Files

Out.xml animation files under the Anim folder

<?xml version= "1.0" encoding= "Utf-8"?> <set xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  android:shareinterpolator=" false >
  <!--100%p P refers to the 100%--> <!--from the specified position of the parent view to the starting bit.
  Displacement-->
   <translate
    android:fromxdelta= "0%p"
    android:toxdelta= "
    100%p" "android:duration=" 1000 "
    />
   <!--transparency--> <alpha android:fromalpha=" 1.0 "android:toalpha="
    0.5 " 
    android:duration= "/>"   
</set>

12, import the RAW load database into the Mobile folder

Private Sqlitedatabase OpenDatabase (String dbfile) {

    try {
      if (!) (! New file (DBFile). Exists ())) {
        //To determine whether the database file exists, if not, to perform an import, otherwise open the database directly
        InputStream is = this.context.getResources ( ). Openrawresource (r.raw.china_city); To import the database
        fileoutputstream fos = new FileOutputStream (dbfile);
        byte[] buffer = new Byte[buffer_size];
        int count = 0;
        while ((count = is.read (buffer)) > 0) {
          fos.write (buffer, 0, count);
        }
        Fos.close ();
        Is.close ();
      }
      Return sqlitedatabase.openorcreatedatabase (DBFile, null);
    } catch (FileNotFoundException e) {
      plog.e ("File not Found");
      E.printstacktrace ();
    } catch (IOException e) {
      plog.e ("IO exception");
      E.printstacktrace ();
    }

    return null;
  }

13, double repel out application

 
public class Doubleclickexit {
  /**
   * Double repel out detection, threshold 2000ms
   /public
  static long Lastclick = 0L;
  private static final int THRESHOLD = 2000;//2000ms public
  static Boolean check () {
    Long now = System.currenttimem Illis ();
    Boolean B = Now-lastclick < THRESHOLD;
    Lastclick = Now;
    return b;
  }
}
  @Override public
  void onbackpressed () {
    if (! Doubleclickexit.check ()) {
        Toastutil.showshort (getString (R.string.double_exit));
      } else {
        finish () ;
      }
  }

14 EditText Some settings:

Set the display type of the soft keyboard after clicking, numberdecimal number with decimal
android:inputtype= "Numberdecimal"
//Setting EditView in Alertdialog Auto Eject soft keyboard
 Editview.setonfocuschangelistener (new View.onfocuschangelistener () {
      @Override public
      Void Onfocuschange (View V, boolean hasfocus) {
        if (hasfocus) {
          //Set eject soft keyboard
          Alertdialog.getwindow (). Setsoftinputmode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
      }
    );

Calendar

Mcalendar= calendar.getinstance ()//Get current date
    int_year = Mcalendar.get (calendar.year);
    Int_month = Mcalendar.get (calendar.month);
    Int_dat = Mcalendar.get (calendar.day_of_month);
    Int_lastday=mcalendar.getactualmaximum (calendar.day_of_month);
    Int_week = Mcalendar.get (Calendar.day_of_week);

16 Dialogfragment, Dialogfragment officially recommended use, the benefits are not much to say

public class Yourdialogfragment extends Dialogfragment {public
 

  interface dialogfragmentdataimp{// Defines an interface that communicates with the activity, and the activity using the Dialogfragment must implement the interface
    void ShowMessage (String message);

  public static yourdialogfragment newinstance (String message) {
    //create a fragment instance with parameters
    Yourdialogfragment fragment = new Yourdialogfragment ();
    Bundle Bundle = new Bundle ();
    Bundle.putstring ("message", message);
    Fragment.setarguments (bundle);//pass parameters to the dialogfragment return
    fragment;
  }
  @Override public
  Dialog oncreatedialog (Bundle savedinstancestate) {
    View CustomView = Layoutinflater.from ( Getactivity ()). Inflate (
        r.layout.fragment_edit_bill_dialog, null);
    Butterknife.bind (This,customview);
    Mcontext = Getactivity ();

    Initview ();

    return new Alertdialog.builder (Getactivity ()). Setview (CustomView)
        . Create ();
  

To use (Invoke in activity or fragment):

 Yourdialogfragment dialog = new Yourdialogfragment ();
    Dialog.show (Getfragmentmanager (), "Logindialog");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.