我查了很多关于如何保存int变量的教程,但我找不到很好的例子。我的代码如下所示:如何使用SharedPreferences保存int?
package com.example.countryclicker;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int exp,level,count,totalCount;
Button mainButton;
TextView current,total;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainButton = (Button) findViewById(R.id.button1);
current = (TextView) findViewById(R.id.TcurrentCount);
total = (TextView) findViewById(R.id.TtotalCount);
mainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
count+=1;
current.setText("Your current count is "+ count);
totalCount = count;
total.setText("Your total count is " + totalCount);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
所以,我有一个整数计数器,从而增加每次我点击一个按钮,但我想,只要用户点击该按钮,程序保存的值到其他整数,即使用户关闭应用程序,该值仍会保留。
是的,这正是我需要 – user2157520 2014-10-29 18:08:25
我在行得到错误的 TOTALCOUNT = pref.getInt( “INT_KEY”,TOTALCOUNT); 或 SharedPreferences.Editor editor = pref.edit(); – user2157520 2014-10-29 19:24:44
@ user2157520你会得到什么错误? – user2336315 2014-10-29 20:58:38