SharedPreference数据的读写操作

SharedPreference是一种轻量型的数据存储方式,它的本质是基于XML文件存储Key-Value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/

shared_prefs目录下。SharedPreference对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。

代码:

<LinearLayout xmlns:android=""

xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/editText1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" > </EditText> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="读取数据" /> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="写入数据" />

</LinearLayout>

import android.os.Bundle;import android.preference.Preference;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {static final String KEY= "MyValue";private EditText et;private Button readbtn,writebtn;SharedPreferences sharedPreferences;Editor editor;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et = (EditText) findViewById(R.id.editText1);readbtn = (Button) findViewById(R.id.button1);writebtn = (Button) findViewById(R.id.button2);sharedPreferences = getPreferences(Activity.MODE_PRIVATE);editor = sharedPreferences.edit();readbtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String in = sharedPreferences.getString(KEY, "当前数值不存在");Toast.makeText(getApplicationContext(), in, Toast.LENGTH_SHORT).show();}});writebtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {editor.putString(KEY, et.getText().toString());if (editor.commit()) {Toast.makeText(getApplicationContext(), "写入成功", Toast.LENGTH_SHORT).show();}}});}}

此时,若写入数据,,会弹出“写入成功”字样;之后可读取数据。

婚姻犹如一艘雕刻的船,看你怎样去欣赏它,又怎样驾驭它。

SharedPreference数据的读写操作

相关文章:

你感兴趣的文章:

标签云: