Joh*_*ohn 0 android sharedpreferences
我正在制作一个计算班级人员BMI的应用程序,其中一个要求是我们使用共享首选项将计算的BMI发送到第二个活动.我的问题是,虽然我在运行应用程序时没有收到任何错误,但我认为没有任何错误发送.
这是我在启动时运行的主要活动.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.btn1);
final EditText Weight = (EditText)findViewById(R.id.txtWeight);
final EditText Height = (EditText)findViewById(R.id.txtHeight);
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
//the bmi calculation
// bmi = (weight * 703) / (height*height);
bmi = weight * height;
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key1", weight);
editor.putInt("key2", height);
editor.putInt("key3", bmi);
final boolean commit = editor.commit();
}
}
);
}
Run Code Online (Sandbox Code Playgroud)
这是我的第二个活动,应该显示从第一个活动发送的BMI.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int weight = sharedPref.getInt("key1", 0);
int height = sharedPref.getInt("key2", 0);
int bmi = sharedPref.getInt("key3", 0);
TextView txtBmi = (TextView) findViewById(R.id.txtBmi);
//error here
txtBmi.setText(Integer.toString(bmi));
Run Code Online (Sandbox Code Playgroud)
当我的应用程序进入第二个屏幕时,textview中显示的唯一内容是0.如果有人可以帮助我找到我的错误,将不胜感激.
请注意,您无法在保存数据之前加载数据.在您的代码中,首先启动活动,然后将数据保存在SharedPreferences中.这意味着第二个活动尝试在保存数据之前加载数据.
更重要的是,这不是您问题的正确解决方案.SharedPreferences旨在存储应用程序使用之间应持续存在的数据,例如用户名或游戏分数.要在活动之间传递数据,您应该使用该Intent.putExtra()方法.
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |