Clanket
Clanket

Reputation: 1289

ListView not shown when adapter is set second time

I got 2 different activities that I change between. But when I go to the second activity and press back the ListView isn't shown. I can't seem to find what's the problem.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    currentLayout = R.layout.activity_main;
    db = new TodoDbHelper(this);
    todos = db.getAllTodos();
    nrOfTodos = todos.size();

    //For ListView
    mListView = (ListView) findViewById(R.id.gradientBackground);
    mAdapter = new TodoAdapter<String>(this, R.layout.text_view_item_default);
    mListView.setAdapter(mAdapter);

    //Calculate height of screen
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    listItemSize = height/10;
    SCREEN_WIDTH = width;        

    createTodoItems();

}

public void createTodoItems() {
    refresh();
    mAdapter.clear();
    for(int i = 0; i < nrOfTodos; i++) {
        String title = todos.get(i).getTitle();

        mAdapter.add(title);
        //System.out.println(title);
        //System.out.println(mAdapter);

    }
    mListView.setAdapter(mAdapter);         
    ImageButton b = (ImageButton) findViewById(R.id.addButton);
    b.bringToFront();
}

public void refresh() {
    todos = db.getAllTodos();
    nrOfTodos = todos.size();
}

@Override
public void onBackPressed() {
    System.out.println("" + this.findViewById(android.R.id.content).getRootView());
    System.out.println("" + currentLayout);
    if(R.layout.activity_add_todo == currentLayout) {
        setContentView(R.layout.activity_main);
        currentLayout = R.layout.activity_main;

        createTodoItems();
        Log.d("onBackPressed", "We're going back.");
    }

}

I do the same "createTodoItems()" both time but then second time it doesn't seem to matter.

Also it seems that mAdapter is the same after the second createTodoItems(). The values in mAdapter is still the same.

Same problem when adding a new item. It just wont render anything from the ListView.

Upvotes: 1

Views: 984

Answers (1)

Fuong Lee
Fuong Lee

Reputation: 195

Try to add this function notifyDataSetChanged(), may it help:

public void createTodoItems() {
   refresh();
   mAdapter.clear();
   for(int i = 0; i < nrOfTodos; i++) {
      title = todos.get(i).getTitle();

      mAdapter.add(title);
      //System.out.println(title);
      //System.out.println(mAdapter);

   }
   mListView.setAdapter(mAdapter);  
   mAdapter.notifyDataSetChanged();   
   ImageButton b = (ImageButton) findViewById(R.id.addButton);
   b.bringToFront();
}

Upvotes: 1

Related Questions