码迷,mamicode.com
首页 > 移动开发 > 详细

Android保存之SharedPreferences

时间:2015-08-01 11:28:00      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Android中一共有四种存储方式:

SharedPreferences 为其中的一种,具体还是看代码:

package com.wyl.preferencetest;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.os.Build;
import android.preference.PreferenceManager;

public class MainActivity extends ActionBarActivity {
	SharedPreferences pref ;
	String username;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//1 获取到preference的两种方式:
//		pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
		pref = getSharedPreferences("myOwn", MODE_PRIVATE);
		//2.使pref可编辑,获得一个可编辑对象
		Editor editor = pref.edit();
		editor.putString("yourname", "wyl");
		editor.putInt("age", 26);
		//3提交编辑,否则不成效的
		editor.commit();
		editor.putBoolean("flag", true);
		editor.putBoolean("flag2", true);
		editor.remove("flag");
		editor.commit();
		String myname = pref.getString("yourname","yourname");
		System.out.println("myname:"+myname);
		MainActivity.this.username = myname;
		
	}

	public void btnOclick(View v){
		if(R.id.btn01==v.getId()){
			System.out.println("======"+this.username);
//		Toast.makeText(MainActivity.this, username+",你登陆成功了", 1000).show();//一定要加.show()方法
		Toast.makeText(MainActivity.this, "this is the toast content", Toast.LENGTH_LONG).show();//
		}
	}

}

  效果图如下:

技术分享

 

技术分享

Android保存之SharedPreferences

标签:

原文地址:http://www.cnblogs.com/Sunnor/p/4693817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!