【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));
	}
}

在这里插入图片描述

发布了73 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40110781/article/details/104933616
今日推荐