Do i have to declare something in android manifest? I’m trying to have text input that is in notes.java save even when the activity is destroyed. So i used SharedPreferences. “editText1” is the text input in notes.xml When i run the app it force closes Here’s notes.java:
public class notes extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
private EditText mEditText;
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String savedText = settings.getString("text", "");
mEditText = (EditText) findViewById(R.id.editText1);
mEditText.setText(savedText);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("text", mEditText.getText().toString());
// Commit the edits!
editor.commit();
}
}
Here’s the Logcat for when it force closes:
03-17 16:54:42.302: E/AndroidRuntime(14558): FATAL EXCEPTION: main
03-17 16:54:42.302: E/AndroidRuntime(14558):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{izzy.n/izzy.n.notes}: java.lang.NullPointerException
03-17 16:54:42.302: E/AndroidRuntime(14558): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1821)
03-17 16:54:42.302: E/AndroidRuntime(14558): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1842)
03-17 16:54:42.302: E/AndroidRuntime(14558): at
android.app.ActivityThread.access$1500(ActivityThread.java:132) 03-17
16:54:42.302: E/AndroidRuntime(14558): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
03-17 16:54:42.302: E/AndroidRuntime(14558): at
android.os.Handler.dispatchMessage(Handler.java:99) 03-17
16:54:42.302: E/AndroidRuntime(14558): at
android.os.Looper.loop(Looper.java:150)
You need to call
setContentViewbeforefindViewById: