我正在尝试动态设置文本视图的文本属性。但是让应用程序强制关闭。我下面的代码有什么问题?
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();
}
}
}