0

In my activity I have the ActionBar with an action button new(that adds a new item on the ListView) and a ListView. The problem is that after I add some items and then I press back button, the ListView returns to the previous ListView with an item less and after one/two seconds shows the complete listviews with all items. I think the problem is something like the listview duplicate one over the previous. Here is my activity:

public class ListNotesActivity extends ActionBarActivity {

private ArrayList<Note> notes;
private Database db;
private long lastBackPressTime = 0;
private Toast toast;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_notes);
    notes = new ArrayList<Note>();
    db = new Database(this);
    getNotes();
    ActionBar ab = getSupportActionBar();
    ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#E89619")));
    ab.setTitle("Your notes");
}

@Override
public void onBackPressed() {
    if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
        toast = Toast.makeText(this, "Press back again to exit", 4000);
        toast.show();
        this.lastBackPressTime = System.currentTimeMillis();
    } else {
        if (toast != null) 
            toast.cancel();
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.list_notes, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    switch (id) {
    case R.id.action_new:
        //In this activity that I start, It will save the new Item in the database and then it starts this activity again that will read the database with the new item.
        Intent i = new Intent(ListNotesActivity.this,
                NotesActivity.class);
        i.putExtra(NEWNOTE, true);
        startActivity(i);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void getNotes() {
    final Toast t = Toast.makeText(this, R.string.retrieving_notes,
            Toast.LENGTH_SHORT);
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            notes = db.getNotes();
            Log.v("MyActivity",
                    "Read notes on the database: " + notes.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            populateList();
        }
    };
    t.show();
    task.execute();
}

public void populateList() {
    NoteAdapter adapter = new NoteAdapter(this, notes);
    final ListView listView = (ListView) findViewById(R.id.list_notes);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parentView, View childView,
                int position, long id) {
            Note note = notes.get(position);
            Log.v("MyActivity",
                    "LISTNOTESACTIVITY: note's title: " + note.getTitle());
            Bundle b = new Bundle();
            b.putSerializable(EDITNOTE2, note);
            Intent i = new Intent(ListNotesActivity.this,
                    NotesActivity.class);
            i.putExtra(EDITNOTE, true);
            i.putExtra(EDITNOTE2, b);
            startActivity(i);
        }
    });
}

I hope I made me clear. Thanks in advance!

1
  • Put your refresh code in onResume() of your activity. Commented Sep 14, 2014 at 14:09

2 Answers 2

1

try to remove this line from your getNotes() Method

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
Sign up to request clarification or add additional context in comments.

Comments

1

Your list view is update only when activity is created ( not when is resumed ) , because you call getNotes() only in onCreate(). In method getNotes(), you make asynch operation.

If you want to update immediately your list view, should take strategy like this.

  1. Start new activity for result, and in second activity after create new item pass data back to the first.

In NotesActivity after create new item add and call this method

private void saveItem(Note note)
{
     Intent data = new Intent();
     // set all data from your item
     data.putExtra(name, value);
     setResult(RESULT_OK, data);
}

In ListNotesActivity you should start new activity by using this call

startActivityForResult(intent, 1);

And override this method

@Override
protected void onResume()
{
    super.onResume();
    // This call on your list view to update rows
    listViewAdapter.notifyDataSetChanged();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(resultCode == RESULT_OK && requestCode == 1)
    {
        Note note = new Note();
        // Extract your data from intent 
        data.getExtra(name); // and set to note variable

        // add your new item to list view adapter
        listViewAdapter.addNewItem(note);
    }
}

I hope this will help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.