1

So, I have a simple app which tracks the calories and fat I take in in a day and totals them for me. works fantastically in portrait orientation, but when I go into landscape, the listview is destroyed, and it seems that the array adapter is also empty. I have boon all over StackOverflow and tried several answers, but none are working. I was under the impression that when the orientation changed, the activity got re-created in onCreate() and that the listView would re-populate from there

Some of the solutions I have tried

1. Handle orentatin changes myself

by overriding onConfigurationChanged() as per this SO answer How to handle an AsyncTask during Screen Rotation?

2. Override onResume() to recreate the listview

what I don't understand about this solution is that to my understanding onResume is called after onCreate anyway, so the listview wold have been recreated already

3. Referenced this opensource code for a simalar app (uses the above onResume method)

https://github.com/Asdamp/Xday/blob/master/src/com/asdamp/x_day/MainActivity.java

I figure there is something wrong in oncreate, so here is that code

  private  ListView foodItemsList;
private DatabaseHelper db;
private ArrayList<FoodItem> allFoods;
private  FoodArrayAdapter foodsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    db = new DatabaseHelper(this);

    setContentView(R.layout.activity_list_foods);
    foodItemsList=(ListView)findViewById(R.id.food_items_list);
    allFoods= (ArrayList<FoodItem>) db.getTodaysFoods();
    foodsAdapter = new FoodArrayAdapter( this, allFoods);



    // set the footer for the list
    View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.food_list_footer, null, false);
    foodItemsList.addFooterView(footerView);
    foodItemsList.setFooterDividersEnabled(true);

    //set the listview to use this adapter
    foodItemsList.setAdapter(foodsAdapter);

       updateTotalDailyCalories();
        updateTotalDailyFat();


}

at a loss here, any help here would save my but The real mistory is that the array list is null after orientation change.........

EDIT: my onResume was wrong

This code fixed the issue

protected void onResume() {
    super.onResume();

    // check if the listview is null
    if (foodItemsList==null){
        // get a refference to it and re create it

        foodItemsList= (ListView) findViewById(R.id.food_items_list);
        // get the data again
        allFoods=(ArrayList<FoodItem>)db.getTodaysFoods();
        foodsAdapter.setListData(allFoods);
        foodsAdapter.notifyDataSetChanged();
    }
}

I Still Dont understand why onResume needs to do that, when onCreate already populates the listview, and is called on orientation changes anyway. Can someone enlighten me?

Community
  • 1
  • 1

0 Answers0