Androsh Training Day: The use of sharedpreferences to achieve data preservation and reading, and the realization of mobile phone call backup, XMLserializer

Source: Internet
Author: User

First, the use of sharedpreferences to achieve data preservation and reading:

1, Mainactivity:

Package Com.example.sharedpreferencesdemo;import Com.example.sharedpreferencesdemo.util.SharedPreferencesUtil; Import Android.app.activity;import Android.app.alertdialog;import Android.content.context;import Android.content.dialoginterface;import Android.content.intent;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Android.os.bundle;import Android.text.textutils;import Android.view.view;import Android.widget.checkbox;import Android.widget.edittext;import android.widget.Toast; public class Mainactivity extends Activity {private EditText et_name, et_pass;private CheckBox chbx_rem;private String fil ename = "Csdn";p rivate sharedpreferencesutil sputil; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); et_name = (EditText) findViewById ( R.id.et_name); et_pass = (EditText) Findviewbyid (r.id.et_pass); Chbx_rem = (CheckBox) Findviewbyid (R.ID.CHBX_REM);// Tool class SPU for instantiating parameter settingstil = new Sharedpreferencesutil (this);//Operation Initedittextdata ();} /** * Initialize the default value of the control */private void Initedittextdata () {//Get parameter Settings object Sharedpreferences SP = this.getsharedpreferences (FileName, context.mode_private);//Gets the corresponding value value by the key value string userName = sp.getstring ("name", "Default"); String Userpass = sp.getstring ("Pass", "Default");//Set the control's default value Et_name.settext (UserName); Et_pass.settext (Userpass);} public void Login (View v) {final string userName = Et_name.gettext (). toString (); final string userpass = Et_pass.gettext (). ToString (); if (Textutils.isempty (userName) | | Textutils.isempty (Userpass)) {Toast.maketext (this, "User name and password cannot be empty", Toast.length_long). Show ();} else {if (chbx_ Rem.ischecked ()) {//Save operation Sputil.save (FileName, Context.mode_private, UserName, userpass);//Login verification//Login Successful Intent Intent = New Intent (); Intent.setclass (this, successactivity.class); startactivity (Intent);} else {new Alertdialog.builder (this). Setmessage ("Please tick the remember password to facilitate next login"). Setnegativebutton ("No", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {//Login verification//Login Successful Intent Intent = new intent (); Intent.setclass (mainactivity . this, successactivity.class); startactivity (intent);}}). Setpositivebutton ("Yes", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {chbx_rem.setchecked (true);//Set Check password//save operation Sputil.save (Filename,context.mode_private, Username,userpass) ;}}). Create (). Show ();}}}


2, the implementation of the Sharedpreferencesdemo method:

Package Com.example.sharedpreferencesdemo.util;import Android.content.context;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Com.example.sharedpreferencesdemo.mainactivity;public class Sharedpreferencesutil {private Context context;/** * constructor * * @param context *: Passed over contextual object */public Sharedpreferencesutil (context context) {This.context = context;} /** * Save Operation * * @param fileName *: File name * @param mode *: File mode * @param userName *: Username * @param userpass *: password */public void Save (string fileName, int mode, string userName, String userpass) {SHAREDPR Eferences sp = context.getsharedpreferences (fileName, mode); Editor editor = Sp.edit (); editor.putstring ("name", UserName), editor.putstring ("Pass", Userpass); Editor.commit ();} /** * Save Operation * * @param mode *: File mode * @param userName *: User name * @param userpass *: Password */pu Blic void Save (int mode, string userName, string useRpass) {mainactivity activity = (mainactivity) context;//contextual object, shape for mainactivity object,// The default is to use the class name to save the file sharedpreferences sp = activity.getpreferences (mode); Editor editor = Sp.edit (); editor.putstring ("name", UserName), editor.putstring ("Pass", Userpass); Editor.commit ();}}

Thinking:

What is the difference between overloading a method in Java and overriding (overwriting) a method

Method overloading means that the return type of the method name and method are the same, but the method parameters are not the same. Parameters differ in the number of arguments and parameter types.

Method overrides: Method overrides are relative to inheritance. The overridden method name. The return type, the parameter type, and the number of arguments are required to be the same as in the parent class. This is the difference between overloading and rewriting forms. When a class inherits a class. Some properties and methods have also been inherited. This allows you to invoke a method in the parent class with a subclass object. But if you are not satisfied with the methods in the parent class, you can override the methods in the parent class. Implement the features you want!!!

Second, the use of XmlSerializer to achieve phone phone backup, including the generation of XML file, and then read it out


First create a user class that encapsulates some entity information:

Package Www.example.domain;import java.io.serializable;/** * <users> <user> <name> Chen Hong all 1</name > <phone>15631293221</phone> * <email>[email protected]</email> <address> Baoding Grade Road, Dongfeng East Road 991</addres> </user> * </users> * * @author June * */public class user implements Serializab  Le {private string name;//name private string phone;//phone private string email;//mailbox private string address;//address public User () {super ();//TODO auto-generated constructor stub}public User (string name, string phone, string email, string address) {Su Per (); this.name = Name;this.phone = Phone;this.email = Email;this.address = Address;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getphone () {return phone;} public void Setphone (String phone) {this.phone = phone;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;}}

One more userservice. To create a contact's information:


Package Com.example.service;import Java.util.arraylist;import Java.util.list;import www.example.domain.User;public Class UserService {public list<user> findAll () {//Declaration returns object List<user> users = new arraylist<user> ();  Simulate 9 person information for  (int i=1;i<=9;i++) {   User user = new User ("Chen Hong All" +i, "1563129322" +i, "[email protected]", " No. 1th Baoding Road, Dongfeng East Road, "+i";   Users.add (user);  } Remember to change the return value to users;}}

The main operations are then performed on the mainactivity:

Package Com.example.activityf;import Java.io.file;import Java.io.fileoutputstream;import java.io.IOException; Import Java.util.list;import www.example.domain.User;import Android.app.activity;import Android.os.bundle;import Android.os.environment;import Android.view.view;import Android.widget.toast;import Com.example.service.userservice;public class Mainactivity extends Activity {private UserService userservice;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); userservice = new UserService ();} /** * detects if your external storage device is installed and is readable and writable * * @return */public boolean isexternalstorageavailable () {//declares the variable returned by Boolean flag = false; Gets the status of the device string state = Environment.getexternalstoragestate ();//Determines whether the device is installed, and whether it is readable and writable if (Environment.media_ Mounted.equals (state)) {//returns True flag = true;} Remember to change the return variable to flag;} /** * operation of backup Phone information * * @param v */public void Copyphoneinfo (View v) {//Get all contact information list<user> users = Userservice.finda ll();//write XML file StringBuffer sb = new StringBuffer ();//write the content to be written with this SB to encapsulate Sb.append ("<?xml version= ' 1.0 ' encoding= ' utf-8 ' Standalone= ' yes '?> ") sb.append (" <users> "), for (User u:users) {sb.append (" <user> "); Sb.append (" < Name> "), Sb.append (U.getname ()) sb.append (" </name> "); Sb.append (" <phone> "); Sb.append (U.getphone () ); Sb.append ("</phone>"); Sb.append ("<email>"); Sb.append (U.getemail ()); Sb.append ("</email>"); Sb.append ("<address>"); Sb.append (U.getaddress ()); Sb.append ("</address>"); Sb.append ("</user>" );} Sb.append ("</users>");//Detect SDcard status if (Isexternalstorageavailable ()) {//Create saved file object Environment.getexternalstoragedirectory (), "Phone.xml"); try {//Create a file's output stream object based on the saved file FileOutputStream fos = new FileOutputStream (file);//write Data Fos.write (sb.tostring (). GetBytes ());//write Fos.flush immediately ();//close Operation Fos.close (); Toast.maketext (This, "Data backup succeeded", Toast.length_long). Show (); catch (IOException e) {e.printstacktrace ();}} else {TOast.maketext (This, "data cannot be backed up (please check your sdcard)", Toast.length_long). Show ();}} 




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.