我正在尝试动态设置文本视图的text属性。但让应用程序部队关闭。我的下面的代码有什么问题?
public class DataStorageActivity extends Activity {
/** Called when the activity is first created. */
public static final String PREFS_NAME = "MyPrefsFile";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor=settings.edit();
editor.putInt("myValue", 7);
editor.commit();
TextView tv=(TextView)findViewById(R.id.textView);
int value=settings.getInt("myValue", 0);
tv.setText(value);
}
}
修改
根据@agamov我已经解决了上述问题。但是,即使将字符串类型传递给setText方法,我也遇到了与下面代码相同的问题。这有什么问题?
public class InternalStorageActivity extends Activity {
public String fileName="HelloFile";
public TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String helloString="Hello";
byte[] b = null;
try {
FileOutputStream fos=openFileOutput(fileName, MODE_PRIVATE);
fos.write(helloString.getBytes());
fos.close();
FileInputStream fis=openFileInput(fileName);
fis.read(b);
String input=b.toString();
textview=(TextView)findViewById(R.id.textView);
textview.setText(input);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您正在将int传递给TextView。 这应该可以解决你的错误:
int value=settings.getInt("myValue", 0);
tv.setText("" + value);