Akhilesh Chobey
Akhilesh Chobey

Reputation: 77

Data not updating on pressing back button

I am making a note taking app using Shared Preferences. However when I click on a listItem to edit it, and click back again, it isn't being updated.

My MainActivity with the list view :

ListView notesListView;
static ArrayList<String> notesArrayList;
static ArrayAdapter<String> notesAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    notesArrayList = new ArrayList<String>();

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

    notesArrayList.add("Example");

    notesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, notesArrayList);

    notesListView.setAdapter(notesAdapter);

    notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getApplicationContext(), EditNote.class);
            intent.putExtra("position", position);
            startActivity(intent);
        }
    });

And my edit note activity:

EditText userNote;
int noteId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_note);

    userNote = (EditText) findViewById(R.id.editTextNote);

    Intent intent = getIntent();
    noteId = intent.getIntExtra("position", -1);
    if(noteId != -1){

        userNote.setText(MainActivity.notesArrayList.get(noteId));

    }
    userNote.addTextChangedListener(this);

}

@Override
public void onBackPressed() {
    Intent goBack = new Intent(EditNote.this, MainActivity.class);
    startActivity(goBack);
    finish();
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
        MainActivity.notesArrayList.set(noteId, String.valueOf(s));
        MainActivity.notesAdapter.notifyDataSetChanged();
}

@Override
public void afterTextChanged(Editable s) {

}
}

I think the problem lies in the onBackPressed in Edit Note. However I would like a solution as I fail to find one.

Upvotes: 1

Views: 644

Answers (1)

Harshad Pansuriya
Harshad Pansuriya

Reputation: 20930

first of all in your this

@Override
public void onBackPressed() {
    Intent goBack = new Intent(EditNote.this, MainActivity.class);
    startActivity(goBack);
    finish();
}

change it to this

  @Override
    public void onBackPressed() {  
        super.onBackPressed();
        this.finish();
    }

because why are you starting MainActivity.java again when you are already going to MainActivity.java on simply onBackPressed() method.

Upvotes: 1

Related Questions