android--User Login and save the user name and password

Source: Internet
Author: User

The previous learning process has finished learning Android, but in the next nearly a year has not been developed Android, so all the knowledge of Android is a little forgotten, so will continue to learn Android, make this study notes. In addition: Because in the summer time to develop the Android project, so for these Android knowledge points are also proficient in mastering.

Directory

One, the JUnit test under Android

Second, the login record password interface design

Third, the use of ROM to save user data

  One, the JUnit test under Android

In real-world development, the process of developing Android software needs to be constantly tested. Using the JUnit test framework, the side is the required technology for regular Android development, and in junit you can get components that simulate the correctness of sending events and detecting program processing.

First build a new Android project, here I named: JUnit, then write the Androidmanifest.xml file, add the Uses-library and instrumentation two properties, the code is as follows:

 1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "3 package=" Lq.wangzhen.junit "4 android:versioncode=" 1 "5 android:versionname=" 1.0 "> 6 7 &lt ; instrumentation 8 Android:name= "Android.test.InstrumentationTestRunner" 9 android:label= "Tests for My App         "Ten android:targetpackage=" Lq.wangzhen.junit "/>11 <uses-sdk13 android:minsdkversion=" 8 "14 android:targetsdkversion= "8"/>15 <application17 android:allowbackup= "true" android:i         con= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" >21 <uses-library android:name= "Android.test.runner"/>22 <activity24 android:name= "LQ.W                 Angzhen.junit.DemoActivity "android:label=" @string/app_name ">26 <intent-filter>27 <action Android:naMe= "Android.intent.action.MAIN"/>28 <category android:name= "Android.intent.category.LAUNCHER"/& gt;30 </intent-filter>31 </activity>32 </application>33 </manifest>

Where the targetpackage configured in instrumentation is the package where the test class is located, I have the package name here: Lq.wangzhen.junit

After writing the above code, you can define a class in the Lq.wangzhen.junit package that contains an Add method, and then we do the testing of this method. The code is as follows:

Services.java

1 package lq.wangzhen.junit; 2  3 public class Service {4  5     /** 6      * Provides a method to receive two integer data 7      * @param x 8      * @param y 9      * @return      */11 public     static int add (int x,int y) {         return x+y;13     }14}

The following is a test class, named: Testaddservice.java, which must be integrated androidtestcase to be used as a test class with the following code:

1 package lq.wangzhen.junit; 2  3 import junit.framework.Assert; 4 import android.test.AndroidTestCase; 5  6 public class Testaddservice Extends Androidtestcase {7  8 public     void Testadd () {9         int result = Service.add (3, 5);         Assert.assertequals (8, result);     }12}

The above is a simple Android test process

  Second, the login record password interface design

After completing the above test function, we will complete a simple user login function, now require the user to enter a user name and password, and choose whether to save the user name and password, if you save the user name and password, we want to save in ROM, And then the next time the user opens the software will automatically extract the corresponding user name and password from the file, fill in the Login box, in this section first design the interface, the interface design XML file as follows:

 1 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 2 xmlns:tools= "/HTTP/ Schemas.android.com/tools "3 android:layout_width=" match_parent "4 android:layout_height=" match_parent "5 Android oid:orientation= "Vertical" > 6 7 <textview 8 android:layout_width= "wrap_content" 9 Android:layo ut_height= "Wrap_content" android:text= "@string/username"/>11 <edittext [android:id=] _username "android:layout_width=" fill_parent "android:layout_height= wrap_content"         int= "@string/username"/>17 <textview19 android:layout_width= "Wrap_content" 20 android:layout_height= "Wrap_content" android:text= "@string/password"/>22 <edittext Android         : id= "@+id/et_password" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" 26     android:hint= "@string/password" 27    Android:inputtype= "Textpassword"/>29 <relativelayout Android:layout_widt H= "Fill_parent" android:layout_height= "wrap_content" >34 <button "android:id=" Tton "android:layout_width=" wrap_content "Notoginseng android:layout_height=" Wrap_content "             ndroid:text= "@string/login" android:layout_alignparentleft= "true"/>40 <checkbox41 Android:id= "@+id/cb_remember" android:layout_width= "Wrap_content" android:layout_height= Content "android:text=" @string/remember_password "android:layout_alignparentright=" true "/>4 6 </relativelayout>47 </LinearLayout>

Here's how to start writing the Mainactivity.java file with the following code:

 1 package lq.wangzhen.file; 2 3 Import android.app.Activity; 4 Import Android.os.Bundle; 5 Import Android.text.TextUtils; 6 Import Android.util.Log; 7 Import Android.view.View; 8 Import Android.view.View.OnClickListener; 9 Import android.widget.button;10 Import android.widget.checkbox;11 import android.widget.edittext;12 Import ANDROID.WIDGET.TOAST;13 public class Mainactivity extends Activity implements Onclicklistener {private St atic final String TAG = "mainactivity"; EditText et_username;18 private EditText et_password;19 Priv Ate Button button;20 private CheckBox cb_remember;21 @Override23 protected void onCreate (Bundle Savedinstan         Cestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); 26 27 Et_username = (EditText) This.findviewbyid (r.id.et_username); Et_password = (EditText) This.findviewbyid (R . id.et_password); button = (Button) This.findvieWbyid (R.id.button); cb_remember = (CheckBox) This.findviewbyid (R.id.cb_remember); 31 32 33 Button.setonclicklistener (this);}36 PNs @Override38 public void OnClick (View v) {39// TODO auto-generated Method STUB40 switch (V.getid ()) {$ Case r.id.button:42-St Ring username = Et_username.gettext (). ToString (). Trim (), String password = Et_password.gettext (). ToString (). Trim (); if (Textutils.isempty (username) | | |                 Textutils.isempty (password)) {Toast.maketext (this, R.string.error, Toast.length_short). Show (); 48 return;49}50 if (cb_remember.ischecked ()) {log.i (TAG, "Save username and password," +usern Ame+ ":" +password);}else{53 log.i (TAG, "No user name and password saved," +username+ ":" +password); 54} break;56}57}58 59 60}

The contents of the Strings.xml file used in the above program are as follows:

1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <resources> 3  4     <string name= "App_name" >file< /string> 5     <string name= "Hello_world" >hello world!</string> 6     <string name= "menu_settings ">Settings</string> 7      8     <string name=" username "> User name </string> 9     <string name=" Password "> Password </string>10     <string name=" Login "> Login </string>11 <string     name=" Remember_password "> Remember password </string>12     <string name=" error "> User name and password cannot be empty </string>13 </ Resources>

  Third, the use of ROM to save user data

The following procedures to modify the above, to add the user name and code can be saved to the file function, first create a new service file, to manipulate the file save, the code is as follows:

1 package lq.wangzhen.service; 2  3 import java.io.FileOutputStream; 4  5 import android.content.Context; 6  7 public class Fileservice {8
   
    9     Private Context context;11 public     Fileservice (context context) {         This.context = context;14     }15     /**16      * Save your username and password to your phone ROM17      * @param password Enter the password you want to save      * @param username The name of the user to save is      * @param filename to which file      (*) @return21      */22 public     boolean savetorom (String password, String username,string filename) throws exception{23         //Open a file in private mode         fileoutputstream fos = Context.openfileoutput (filename, context.mode_private);         String result = username+ ":" +password;26         Fos.write (Result.getbytes ());         Fos.flush ();         fos.close ();         return true;30     }31}
   

Modify the Mainactivity.java file with the following code:

 1 package lq.wangzhen.file; 2 3 Import Lq.wangzhen.service.FileService; 4 Import android.app.Activity; 5 Import Android.os.Bundle; 6 Import Android.text.TextUtils; 7 Import Android.util.Log; 8 Import Android.view.View; 9 Import android.view.view.onclicklistener;10 Import android.widget.button;11 import android.widget.checkbox;12 Import android.widget.edittext;13 Import android.widget.toast;14 public class Mainactivity extends Activity Implements Onclicklistener {$ private static final String TAG = "mainactivity"; private EditText Et_user name;19 private EditText et_password;20 private Button button;21 private CheckBox cb_remember;22 private F Ileservice fileservice;23 @Override25 protected void onCreate (Bundle savedinstancestate) {SUPER.ONCR Eate (savedinstancestate); Setcontentview (r.layout.activity_main); et_username = (EditText) This.findviewbyid (r.id.et_username); Et_password = (EditteXT) This.findviewbyid (r.id.et_password); button = (button) This.findviewbyid (R.id.button); cb_remember         = (CheckBox) This.findviewbyid (R.id.cb_remember), Button.setonclicklistener (this); 36  37//Initialization File Service Fileservice = new Fileservice (this),}41 @Override43 Public void OnClick (View v) {//TODO auto-generated Method stub45 switch (V.getid ()) {case R.id.bu tton:47 string username = Et_username.gettext (). toString (). Trim (), and the string passwor D = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (username) | |                 Textutils.isempty (password)) {Toast.maketext (this, R.string.error, Toast.length_short). Show (); 53 return;54}55 if (cb_remember.ischecked ()) {log.i (TAG, "Save username and password," +usern Ame+ ":" +password);ry {* *] Boolean result = Fileservice.savetorom (password, username, "Private.txt"); 59 if (result) {Toast.maketext (Getapplicationcontext (), r.string.success, Toast.length_short). Show ();}else{62 Toast.maketext (Getapplicationcontext (), r.string.failed, Toast. Length_short). Show (),}64} catch (Exception e) {n//TODO Auto -generated catch block66 e.printstacktrace (); Toast.maketext (Getapplicationconte     XT (), r.string.failed, Toast.length_short). Show ();}69}70 break;71}72 }73 74 75}

Add the following content to the Strings.xml file:

1 <string name= "Success" > Saved successfully </string>2 <string name= "Failed" > Save failed </string>

Run the program, save successfully, save the file by default in the Data/data/lq.wangzhen.file/files folder, where Lq.wangzhen.file represents the package name of the activity. Below this program based on the addition of the ability to read the user name and password from the file, first add the following method in the Fileservice.java file to read the contents of the file from ROM.

1 public map<string,string> GetUserInfo (String filename) throws exception{2         File File = new file ("Data/data/lq . wangzhen.file/files/"+filename); 3         FileInputStream fis = new FileInputStream (file); 4         //The two lines above can also be implemented by the following code: 5         //fileinputstream FIS = Context.openfileinput (filename); 6         byte[] data = streamtools.getbytes (FIS); 7         String result = new string (data); 8         string results[] = RESULT.SPL It (":"); 9         map<string,string> Map = new hashmap<string,string> (),         map.put ("username", results[0]); 11         map.put ("password", results[1]);         return map;13     }

A streamtools.getbytes () method is called in this method, which is specifically used to convert a inputstream stream to a byte array, so we write this method as:

1 package lq.wangzhen.util; 2  3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5  6 public class Streamtools {7  8
   /** 9      * Read the contents of the InputStream, put it in a byte[] and return to      @param is11      * @return12      * @throws Exception      * * Public     Static byte[] GetBytes (InputStream is) throws exception{15         Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();         byte[] buffer = new byte[1024];17         int len = 0;18 while         ((Len=is.read (buffer) )! =-1) {             baos.write (buffer, 0, Len);         }21         Baos.flush ();         baos.close ();         Baos.tobytearray ();     }25}

Finally, modify the Mainactivity.java file again, calling the GetUserInfo method written:

 1 package lq.wangzhen.file; 2 3 Import Java.util.Map; 4 5 Import Lq.wangzhen.service.FileService; 6 Import android.app.Activity; 7 Import Android.os.Bundle; 8 Import Android.text.TextUtils; 9 Import android.util.log;10 Import android.view.view;11 import android.view.view.onclicklistener;12 Import ANDROID.WIDGET.BUTTON;13 Import android.widget.checkbox;14 Import android.widget.edittext;15 Import ANDROID.WIDGET.TOAST;16 public class Mainactivity extends Activity implements Onclicklistener {private St atic final String TAG = "mainactivity"; private EditText et_username;21 private EditText et_password;22 Priv Ate Button button;23 private CheckBox cb_remember;24 private fileservice fileservice;25 @Override27 Pro tected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R   . layout.activity_main); et_username = (EditText) This.findviewbyid (r.id.et_username); 32      Et_password = (EditText) This.findviewbyid (r.id.et_password), Button = (button) This.findviewbyid (r.id.but ton); Cb_remember = (CheckBox) This.findviewbyid (r.id.cb_remember); Button.seton Clicklistener (this); 38 39//Initialization file Service Fileservice = new Fileservice (this); y {map<string,string> Map = Fileservice.getuserinfo ("Private.txt"); Et_username.settext             (Map.get ("username")); Et_password.settext (Map.get ("password")); catch (Exception e) {47     TODO auto-generated catch block48 e.printstacktrace (); 49}50 51 52}53 54 @Override55 public void OnClick (View v) {//TODO auto-generated Method stub57 switch (V.getid ()             ) {r.id.button:59 case, String username = Et_username.gettext (). toString (). Trim (); 61 String PASSWOrd = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (username) | |                 Textutils.isempty (password)) {Toast.maketext (this, R.string.error, Toast.length_short). Show (); 65 return;66}67 if (cb_remember.ischecked ()) {log.i (TAG, "Save username and password," +usern Ame+ ":" +password); "Try {$" result = Fileservice.savetorom (password, username , "Private.txt"), if (result) {Toast.maketext (Getapplicationcontext (), R.st Ring.success, Toast.length_short). Show ();}else{74 Toast.maketext (Getapplica Tioncontext (), r.string.failed, Toast.length_short). Show ();}76} catch (Exception E                     {block78//TODO auto-generated catch E.printstacktrace (); 79 Toast.maketext (GetapplicationconText (), r.string.failed, Toast.length_short). Show ();}81}82 break;83}8 4}85 86 87}

The above is the whole content of this study, will continue to the program to make a rest later.

Http://www.cnblogs.com/wukong65/archive/2013/05/04/3059411.html

android--User Login and save the user name and password

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.