在共享首选项中设置/放置数值?
public void onClick(View v) {
switch(v.getId()){
case R.id.save2:
s = text.getText().toString();
number = Float.parseFloat(num.getText().toString());
SharedPreferences.Editor editor = shared.edit();
editor.putString("sharedtext",s);
editor.putFloat("sharednum",number);
editor.commit();
Toast.makeText(this,"save2",Toast.LENGTH_SHORT).show();
break;
case R.id.load2:
String returner = shared.getString("sharedtext","Returner fail");
float returnnum = shared.getFloat("sharednum","number fail");
//there is a red mark here^^^^^^^^^(getfloat)
text.setText(returner);
//num.set.......how will
Toast.makeText(this,"load2",Toast.LENGTH_SHORT).show();
break;
case R.id.page2:
intent= new Intent(this,SharedPreferencesActivity.class);
startActivity(intent);
Toast.makeText(this,"page2",Toast.LENGTH_SHORT).show();
break;
}
//这里有一个红色标记^^^^^^^^^(getfloat) - 一个让我切换到getInt和getFloat的错误
//num.set.......我将如何设置一个数字值?
谢谢
public void onClick(View v) {
switch(v.getId()){
case R.id.save2:
s = text.getText().toString();
number = Float.parseFloat(num.getText().toString());
SharedPreferences.Editor editor = shared.edit();
editor.putString("sharedtext",s);
editor.putFloat("sharednum",number);
editor.commit();
Toast.makeText(this,"save2",Toast.LENGTH_SHORT).show();
break;
case R.id.load2:
String returner = shared.getString("sharedtext","Returner fail");
float returnnum = shared.getFloat("sharednum","number fail");
//there is a red mark here^^^^^^^^^(getfloat)
text.setText(returner);
//num.set.......how will
Toast.makeText(this,"load2",Toast.LENGTH_SHORT).show();
break;
case R.id.page2:
intent= new Intent(this,SharedPreferencesActivity.class);
startActivity(intent);
Toast.makeText(this,"page2",Toast.LENGTH_SHORT).show();
break;
}
//there is a red mark here^^^^^^^^^(getfloat) -an error that keeps me switching into getInt and getFloat
//num.set.......how will i set a number value?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您尝试从首选项中获取值时,您还需要设置一个默认值,如下所示:
you also need to set a default value, when you are trying to getvalues from preferences, like below:
试试这个
try this
float returnnum =shared.getFloat("sharednum","numberfail");
将“numberfail”更改为
float
类型的数字。该参数代表默认值,因此不能使用字符串。float returnnum = shared.getFloat("sharednum","number fail");
Change "number fail" to a number of type
float
. This parameter represents the default value, so you cannot use a string.