Android uses SharedPreferences to save and read files,

Source: Internet
Author: User

Android uses SharedPreferences to save and read files,
Project directory:

For software development, we should know that many software may have configuration files that store the attribute values of the program running. because there are not many configuration information, it is not cost-effective to store them using databases, because the time consumption of database connection and operation greatly affects the program efficiency, we use the one-to-one correspondence relationship of key values to store the configuration information. SharedPreferences is the technology used in Android to implement the storage method. The following code is directly pasted: Package peixun. savaparameter. service;
PreferenceService class:
<span style="font-size:18px;">package peixun.savaparameter.service;import java.util.HashMap;import java.util.Map;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.preference.Preference;public class PreferenceService {private Contextcontext;public PreferenceService(Context context) {super();this.context = context;}public void save(String name, Integer age) {// TODO Auto-generated method stubSharedPreferences preference=context.getSharedPreferences(name, Context.MODE_PRIVATE);Editor editor=preference.edit();editor.putString("name", name);editor.putInt("age", age);editor.commit();}public Map<String,String> getParameter(String name){Map<String, String> params=new HashMap<String, String>();SharedPreferences preference=context.getSharedPreferences(name, Context.MODE_PRIVATE);params.put("name", preference.getString("name", ""));params.put("age", String.valueOf(preference.getInt("age", 0)));return params;}}</span><strong></strong>
Note:// Open Preferences with the name "name". Open Preferences if the Preferences exist. Otherwise, create a new Preferences with the write method "Context. MODE_PRIVATE.
SharedPreferences preference = context. getSharedPreferences (name, Context. MODE_PRIVATE );
Editor editor = preference. edit (); // make the Editor editable.
Package peixun. savaparameter;

MainActivity class:

package peixun.savaparameter;import java.util.Map;import peixun.savaparameter.service.PreferenceService;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText nameText;private EditText ageTest;private PreferenceService service;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);nameText=(EditText) this.findViewById(R.id.name);ageTest=(EditText) this.findViewById(R.id.age);service=new PreferenceService(this);String name=nameText.getText().toString();Map<String, String> paramers=service.getParameter(name);nameText.setText(paramers.get("name"));ageTest.setText(paramers.get("age"));}public void save(View v){String name=nameText.getText().toString();String age=ageTest.getText().toString();PreferenceService service=new PreferenceService(getApplicationContext());service.save(name,Integer.valueOf(age));Toast.makeText(getApplicationContext(), R.string.savaSuccess, 1).show();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}

Activity_main.xml file under the layout directory:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="@string/name"    /><EditText     android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/name"/><TextView     android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="@string/age"/><EditText    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/age"/><Button     android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="@string/savaButton"    android:onClick="save"    android:id="@+id/saveButton"/>    </LinearLayout>

String. xml file in the values directory

<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "app_name"> Save parameters </string> <string name = "action_settings"> Settings </string> <string name = "name"> name </string> <string name = "age"> age </string> <string name = "savaButton"> saved parameter </string> <string name = "savaSuccess"> saved successfully </string> <string name = "savaFailed"> failed to save </string> </resources>

Running result:



There is a shared_prefs File under the data directory under File Explorer. The path strength of the saved File is as follows: the File name is the name we entered.

SharedPreferences is easy to use and can easily store and read data. SharedPreferences can only store simple types of data, such as String and int. Generally, the data of complex types is converted to Base64 encoding, And the converted data is saved as a string in the XML file, and then saved in SharedPreferences.



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.