zoukankan      html  css  js  c++  java
  • Android保存之SharedPreferences

    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();//
    		}
    	}
    
    }
    

      效果图如下:

  • 相关阅读:
    URAL 1207 极角排序
    URAL 1348 求垂足
    POJ 3608 旋转卡壳
    POJ 2954 Pick定理
    POJ 2007 叉积排序
    UVA 10002 凸多边形重心
    [转]bad interpreter:No such file or directory的原因
    [转]实现Python HTTP服务方法大总结
    urllib2.HTTPError: HTTP Error 403: Forbidden 错误
    C++二分查找代码
  • 原文地址:https://www.cnblogs.com/Sunnor/p/4693817.html
Copyright © 2011-2022 走看看