当前位置: 代码迷 >> Android >> Android-SharedPreferences 储存
  详细解决方案

Android-SharedPreferences 储存

热度:380   发布时间:2016-04-28 02:41:48.0
Android--SharedPreferences 存储

.java代码如下:

package org.lxh.demo;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.content.DialogInterface;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnFocusChangeListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class Hello extends Activity {	private static final String FILENAME="mldn";		public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState); // 生命周期方法		super.setContentView(R.layout.main); // 设置要使用的布局管理器				SharedPreferences share=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);		SharedPreferences.Editor edit=share.edit();		edit.putString("author", "zhangyayun");		edit.putInt("age", 30);		edit.commit();	}}
运行后找到文件:

导出后:

下面利用代码读取该信息:

main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/authorinfo"        android:layout_width="fill_parent"        android:layout_height="wrap_content"/>    <TextView        android:id="@+id/ageinfo"        android:layout_width="fill_parent"        android:layout_height="wrap_content"/>    </LinearLayout>

.java代码如下:

package org.lxh.demo;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.content.DialogInterface;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnFocusChangeListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class Hello extends Activity {	private static final String FILENAME = "mldn";	private TextView authorinfo = null;	private TextView ageinfo = null;	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState); // 生命周期方法		super.setContentView(R.layout.main); // 设置要使用的布局管理器		this.authorinfo = (TextView) super.findViewById(R.id.authorinfo);		this.ageinfo = (TextView) super.findViewById(R.id.ageinfo);		SharedPreferences share = super.getSharedPreferences(FILENAME,				Activity.MODE_PRIVATE);		this.authorinfo.setText("作者:" + share.getString("author", "没有作者信息"));		this.ageinfo.setText("年龄" + share.getInt("age", 0));	}}

运行效果如下:



  相关解决方案