0

I'm trying to learn how to make an app; my app crashes when I go to another activity, and then try to go back to my original activity. This is in my oncreate:

Bundle bundle;

        if (savedInstanceState != null){
            bundle = savedInstanceState;
        } else {
            bundle = getIntent().getExtras();
        }

        course = bundle.getString("com.naomi.classAlert.course");
        number = bundle.getString("com.naomi.classAlert.number");

I know that when I tap back from the activity, savedInstanceState is not null; however, why does it crash when I try to get the string from the bundle? How can I fix this? I want the value of course and number to be the same when I continue the activity.

This is my full code:

public class classList extends AppCompatActivity {
    ListView listView;
    SimpleCursorAdapter mAdapter;
    static private String[] classes = {"class1","class2"};

    String course;
    String number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle;

        if (savedInstanceState != null){
            bundle = savedInstanceState;
        } else {
            bundle = getIntent().getExtras();
        }
        course = bundle.getString("com.naomi.classAlert.course");
        number = bundle.getString("com.naomi.classAlert.number");

        Toast.makeText(getApplicationContext(), course+number,
                Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_class_list);

        listView = (ListView) findViewById(R.id.list);


        // ALL THE DIFFERENT SECTIONS
        String[] values = new String[] {
                course+number+" 001", course+number+" 002", course+number+" 003"
        };

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_2, android.R.id.text1, values);
        listView.setAdapter(adapter);

        // ListView Item Click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :"+ itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                        .show();

                Intent intent1 = new Intent(classList.this, pickSection.class);
                intent1.putExtra("com.naomi.classAlert.classList.course",course);
                intent1.putExtra("com.naomi.classAlert.classList.number", number);
                intent1.putExtra("com.naomi.classAlert.classList.section",position+1);
                startActivity(intent1);

            }

        });
    }

    @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putString("com.naomi.classAlert.course", course);
        outState.putString("com.naomi.classAlert.number", number);
    }
}

Log:

10-14 00:16:08.411  19529-19529/com.example.naomikoo.classalert D/OpenGLRenderer﹕ Enabling debug mode 0
10-14 00:16:13.325  19529-19532/com.example.naomikoo.classalert D/dalvikvm﹕ GC_CONCURRENT freed 125K, 2% free 9350K/9504K, paused 4ms+3ms, total 29ms
10-14 00:16:15.254  19529-19529/com.example.naomikoo.classalert D/AndroidRuntime﹕ Shutting down VM
10-14 00:16:15.254  19529-19529/com.example.naomikoo.classalert W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41d3c930)
10-14 00:16:15.262  19529-19529/com.example.naomikoo.classalert E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.naomikoo.classalert/com.example.naomikoo.classalert.classList}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5039)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.naomikoo.classalert.classList.onCreate(classList.java:39)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5039)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

note: this question is not a duplicate, I'm not trying to pass a result from an activity to the previous activity; I'm trying to preserve the state so that it's the same when I go back.

  • Possible duplicate of [How to manage \`startActivityForResult\` on Android?](http://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android) – enigman Oct 14 '15 at 03:38
  • What are you trying to achieve? To save the state of the activity? – Niko Adrianus Yuwono Oct 14 '15 at 03:42
  • @NikoYuwono I'm trying to save and load the state of the activity so that when I go to another activity and then go back, 'course' and 'number' will still have the same values – sesameseedball Oct 14 '15 at 03:43
  • where are you saving course and number to the bundle? Have you overriden `onSaveInstanceState` method? – Akash Singh Oct 14 '15 at 04:07
  • @AkashSingh Yes, I've overriden the onSaveInstanceState method; I'm saving the course and number there, I think (method is at bottom of code) – sesameseedball Oct 14 '15 at 04:08

2 Answers2

0

Change your onSaveInstanceState to the following :

@Override
public void onSaveInstanceState(Bundle outState){

    outState.putString("com.naomi.classAlert.course", course);
    outState.putString("com.naomi.classAlert.number", number);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(outState);

}
Akash Singh
  • 748
  • 1
  • 6
  • 14
  • Unfortunately, it doesn't help; my app still crashes when I try to getString from the bundle in onCreate – sesameseedball Oct 14 '15 at 04:12
  • can you post your log? – Akash Singh Oct 14 '15 at 04:15
  • what does this `bundle = getIntent().getExtras();` statement does in else condition? – Akash Singh Oct 14 '15 at 04:20
  • if the bundle is null, then I get all the extras in the intent; I don't think that part is a problem, since it works fine when it's my first time entering the screen. It only crashes when I go back to that screen – sesameseedball Oct 14 '15 at 04:21
  • can you post how `classList` activity is started from its starting activity? – Akash Singh Oct 14 '15 at 04:22
  • This is the main activity: public void onSubmitClick(View view){ Intent intent = new Intent(this, classList.class); intent.putExtra("com.naomi.classAlert.course",course); intent.putExtra("com.naomi.classAlert.number", number); startActivity(intent); } – sesameseedball Oct 14 '15 at 04:23
  • you are saving and restoring the activity state correctly and I don't see any problem with the code. NPE is most probably caused by some other code of your `Activity`. – Akash Singh Oct 14 '15 at 07:26
0

Do you have the onRestoreInstanceState in your code? Wasn't sure if you have posted in it's entirety.

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
course = savedInstanceState.getString("com.naomi.classAlert.course");
number = savedInstanceState.getString("com.naomi.classAlert.number");
Toast.makeText(getApplicationContext(), "Course: " + course + " ", number: " + number, Toast.LENGTH_LONG).show();
}

I'd also recommend defining a couple of constants and using those instead

public static final String COURSENAME = "com.naomi.classAlert.course"
public static final String COURSENUMBER = "com.naomi.classAlert.number"

Try testing the initialization of the course and number variables:

String course = "No Class";
String number = "99999";

Also try this

if (savedInstanceState != null){
        bundle = savedInstanceState;
        course = bundle.getString("com.naomi.classAlert.course");
        number = bundle.getString("com.naomi.classAlert.number");
        }

From your code, I'm unsure where your course and number is supposed to be assigned from (listview etc) but these would need to be assigned at some point - the code currently places the current values (even if null) into the extra.

enigman
  • 121
  • 4
  • that was my code in its entirety, but I tried adding onRestoreInstanceState; unfortunately, I still get the crash :/ – sesameseedball Oct 15 '15 at 01:32
  • The way I'm reading it, I don't see course or number being initialized other than via the Bundle which would initially be null. Can you try moving the course = bundle.getString and number=bundle.getString within the If condition - after bundle = savedInstanceState; This would need assigning values to course and number as I don't see them being assigned values in your code (e.g from listview, default value etc.) Try assigning a default value to them when declaring them to validate that something else is getting placed there. – enigman Oct 15 '15 at 03:22