标签:android sharedprefer sharedpreferences android设置存储
public class MainActivity extends Activity { private Button write; private Button read; private SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); write = (Button) findViewById(R.id.write); read = (Button) findViewById(R.id.read); preferences = getSharedPreferences("count",MODE_PRIVATE); //读取SharedsPreferences里的count数据 int count = preferences.getInt("count",0); Toast.makeText(this,"程序以前被使用了" + count + "次。 ", Toast.LENGTH_LONG).show(); //获取到SharedPreferences的editor,用来进行写入数据 SharedPreferences.Editor editor = preferences.edit(); //存入数据 editor.putInt("count",++count); //提交修改 editor.commit(); } }
Context context = createPackageContext("com.dada.example",Context.CONTEXT_IGNORE_SECURITY);
public class MainActivity extends ActionBarActivity { private Button write; private Button read; private int count; private SharedPreferences preferences; private SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); write = (Button) findViewById(R.id.write); read = (Button) findViewById(R.id.read); Context myApplication = null; try{ myApplication = createPackageContext("com.example.pc.myapplication",Context.CONTEXT_IGNORE_SECURITY); preferences = myApplication.getSharedPreferences("count",Context.MODE_WORLD_WRITEABLE); editor = preferences.edit(); } catch (Exception e){ e.printStackTrace(); } write.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.putInt("count",++count); } }); read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count = preferences.getInt("count",0); Toast.makeText(getApplicationContext(),"count的值为" + count,Toast.LENGTH_LONG).show(); } }); } }
标签:android sharedprefer sharedpreferences android设置存储
原文地址:http://blog.csdn.net/jing_unique_da/article/details/44095817