(ix) data storage and access in Android-save files to phone memory

Source: Internet
Author: User
Tags gettext save file try catch

9.1 Storage area of the phone

The storage area of the phone is usually two places: one: The internal storage space of the mobile phone, understood as a piece of micro-hard disk/data/data/; second: External storage SD Card

9.2 Methods to catch Exceptions principle

If the method has a return value, it is captured with a try catch, and if the return value of the method is of type void, an exception is thrown with throws

9.3 Contextual Context

Context: is a class that provides some handy APIs to get an application's environment, such as: The environment's package name, installation path, resource path, path to the asset

9.4 Save file to phone memory--Login Interface Example program9.4.1 Project Requirements

User login interface as shown below, when the password is checked to save the user name and password to the phone memory, the next time you open the login screen, will automatically remove the user name and password from the phone memory back to the interface.

the 9.4.2 project directory structure is as follows

9.4.3 activity_main.xml File
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.logintest.MainActivity" > <TextView android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Please enter user name"android:textsize= "18DP"/> <EditText Android:id= "@+id/et_username"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:textsize= "18DP"/> <TextView android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Please enter password"android:textsize= "18DP"/> <EditText Android:id= "@+id/et_pwd"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:inputtype= "Numberpassword"android:textsize= "18DP"/> <Radiogroup Android:id= "@+id/rg_mode"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:orientation= "Horizontal" > <RadioButton Android:id= "@+id/rb_private"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Private"/> <RadioButton Android:id= "@+id/rb_public"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Public"/> <RadioButton Android:id= "@+id/rb_readable"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "readable"/> </RadioGroup> <relativelayout android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content" > <CheckBox Android:id= "@+id/cb_checked"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:checked= "true"Android:text= "Remember Password"android:textsize= "18DP"/> <Button Android:id= "@+id/bt_login"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparentright= "true"Android:text= "Login"android:textsize= "18DP"/> </RelativeLayout> </LinearLayout>
9.4.4 Fileinfo.java File
 PackageCom.example.logintest.service;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.util.HashMap;ImportJava.util.Map;ImportAndroid.content.Context; Public classFileInfo {/*** Save the file to Context.getfilesdir () * *@paramContext * Contexts *@paramUsername * User name *@paramPWD * User password *@return     */     Public Static BooleanSavefileuserinfo (context context, string Username, string Pwd) {File file=NewFile (Context.getfilesdir (), "Userinfo.txt"); //context.openfileoutput (file, mode)        Try{FileOutputStream fos=Newfileoutputstream (file); //Fos.write (username+ "# #" +pwd). Getb;Fos.write ((username + "# #" +Pwd). GetBytes ());            Fos.close (); return true; } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; }    }    /*** Read the user's information from the file and save it in the map object to get the file directory from Context.getfilesdir () *@paramContext *@return     */     Public StaticMap<string, string>GetUserInfo (Context context) {File file=NewFile (Context.getfilesdir (), "Userinfo.txt");        FileInputStream fis; Try{FIS=Newfileinputstream (file); BufferedReader BR=NewBufferedReader (NewInputStreamReader (FIS)); String Str=Br.readline (); String infos[]= Str.split ("# #"); Map<string, string> map =NewHashmap<string, string>(); Map.put ("Username", infos[0]); Map.put ("Userpwd", infos[1]); returnmap; } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); return NULL; }    }}
9.4.5 Mainactivity.java File
 Packagecom.example.logintest;ImportJava.util.Map;ImportCom.example.logintest.service.FileInfo;ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.text.TextUtils;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.CheckBox;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsActivityImplementsOnclicklistener {Private Static FinalString TAG = "Mainactivity"; PrivateEditText Et_username; PrivateEditText et_pwd; PrivateCheckBox cb_checked; PrivateButton Bt_login; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Et_username= (EditText) This. Findviewbyid (R.id.et_username); Et_pwd= (EditText) This. Findviewbyid (R.ID.ET_PWD); Cb_checked= (CheckBox) This. Findviewbyid (r.id.cb_checked); Bt_login= (Button) This. Findviewbyid (R.id.bt_login); Bt_login.setonclicklistener ( This); Map<string, string> map = Fileinfo.getuserinfo ( This); if(Map! =NULL) {Et_username.settext (Map.get ("Username")); Et_pwd.settext (Map.get ("Userpwd")); }} @SuppressLint ("Showtoast") @Override Public voidOnClick (View v) {//TODO auto-generated Method StubString UserName =Et_username.gettext (). toString (). Trim (); String userpwd=Et_pwd.gettext (). toString (). Trim (); if(Textutils.isempty (userName) | |Textutils.isempty (USERPWD)) {Toast.maketext ( This, "User name is empty or user password is empty", 1). Show (); } Else {            if(cb_checked.ischecked ()) {log.i (TAG,"Please save password"); if(Fileinfo.savefileuserinfo ( This, UserName, userpwd)) {log.i (TAG,"User Information saved successfully"); }            }            if("Zhangsan". Equals (UserName) && "123". Equals (USERPWD)) {Toast.maketext ( This, "User Login", 1). Show (); } Else{Toast.maketext ( This, "Landing Failure", 1). Show (); }        }    }}
the 9.4.6 program run interface is shown below

(ix) data storage and access in Android-save files to phone memory

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.