Search code examples
androidlistviewonresumeactivity-lifecycle

onResume causing problems on start up


I have an activity that allows the user to start a second activity. The second activity has a list of items which I add to an array list. When I return to the previous activity I want to display the size of the array list.

However I am having a problem with onResume(). It is called when my first activity is created and as a result generates an error as the array list does not exist when it is first launched!

onResume():

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    getIntentData();
    calcSubTotal(orderData);
}

getIntentData():

public void getIntentData(){
    b = new Bundle();
    b = getIntent().getExtras();
    orderData = b.getParcelable("order");
    Toast.makeText(this.getApplicationContext(), orderData.size(), Toast.LENGTH_LONG).show();
}

onCreate() of second activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starters);
    createTestData();

    b = new Bundle();
    orderData = new MenuItemList();

    adapter = new MenuItemArrayAdapter(this, starters);
    this.setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    Toast.makeText(this.getApplicationContext(), l.getItemAtPosition(position).toString() + " clicked", Toast.LENGTH_LONG).show();
    //add clicked item to orderData....
    MenuItem m = (MenuItem)l.getItemAtPosition(position);
    //create new item
    orderData.add(m);   
}

Any idea how I might be able to control this?

ERROR:

java.lang.RuntimeException: Unable to resume activity {com.example.waitronproto3/com.example.waitronproto3.SectionsActivity}: java.lang.NullPointerException


Solution

  • However I am having a problem with onResume(). It is called when my first activity is created and as a result generates an error as the array list does not exist when it is first launched!

    I recommend changing getIntentData() to check if the appropriate data exists first:

    public void getIntentData(){
        Intent intent = getIntent();
        if(intent != null && intent.hasExtra("order")) {
            orderData = b.getParcelable("order");
            Toast.makeText(this.getApplicationContext(), orderData.size(), Toast.LENGTH_LONG).show();
            calculateSubTotal(order);
        }
    }
    

    And update onResume():

    @Override
    protected void onResume() {
        super.onResume();
        getIntentData();
    }
    

    (Though you could simply put getIntentData() in onResume() now.)