0

I am making a simple Notepad app and have an issue displaying the data in the listview when the return button is pressed on the emulator to go back to the MainActivity where the list is displayed. It only displays the data when I close the app and open it again, then the listview is populated. I have shown my code below.

This my MainActivity where the ListView is present:

package example.mynotepad;

import example.mynotepad.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class MainActivity extends Activity implements OnItemClickListener {

    Button Add_Btn;
    ListView nListView;
    NotesAdapter nAdapter;
    Cursor nCursor;
    public static boolean isDbCreated = false;

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

        Add_Btn = (Button) findViewById(R.id.add_btn);
        Add_Btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent AddNotes = new Intent(MainActivity.this, AddNotes.class);
                startActivity(AddNotes);
            }
        });

        nListView = (ListView) findViewById(R.id.listView1);
        final NotesDbHelper nHelper = new NotesDbHelper(this);
        nHelper.Open();

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                nCursor = nHelper.AllData();
                nAdapter = new NotesAdapter(MainActivity.this, nCursor);
                nListView.setAdapter(nAdapter);
            }
        });

        nListView.setOnItemClickListener(this);
        nListView.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                TextView id = (TextView) v.findViewById(R.id.textView1);
                final int i = Integer.parseInt(id.getText().toString());

                AlertDialog.Builder aDialog = new AlertDialog.Builder(
                        MainActivity.this);
                aDialog.setTitle("Delete Note?");
                aDialog.setMessage("This Will Delete It Permanently?");

                aDialog.setPositiveButton((getString(R.string.Delete)),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface Dialog,
                                    int which) {
                                nHelper.Delete(i); // Delete Method in DBHelper
                                nCursor.requery();
                                nAdapter.notifyDataSetChanged();
                                nListView.setAdapter(nAdapter);
                            }
                        });
                aDialog.setNegativeButton((getString(R.string.Cancel)),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                dialog.dismiss();
                            }
                        });
                aDialog.show();
                return false;
            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position,
            long arg3) {
        TextView noteid = (TextView) view.findViewById(R.id.textView1);
        TextView notetitle = (TextView) view.findViewById(R.id.textView2);
        TextView notebody = (TextView) view.findViewById(R.id.textView3);

        int i = Integer.parseInt(noteid.getText().toString());
        String nt = notetitle.getText().toString();
        String nb = notebody.getText().toString();

        Intent Update = new Intent(MainActivity.this, UpdateNotes.class);

        Update.putExtra("id", i);
        Update.putExtra("ntitle", nt);
        Update.putExtra("nbody", nb);

        startActivityForResult(Update, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case 101:

                nCursor.requery();
                nAdapter.notifyDataSetChanged();
                nListView.setAdapter(nAdapter);
                break;
            }
        }
    }
}

MainActivity XML:

    <LinearLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/add_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="15dp"
        android:text="@string/add_note_btn" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fastScrollEnabled="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:splitMotionEvents="true" >

    </ListView>

</LinearLayout>

This is the Activity to Add Notes:

    package example.mynotepad;

import example.mynotepad.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddNotes extends Activity {

    Button Cancel_Btn, Save_Btn;
    EditText ET_Title, ET_Notes;

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

        Cancel_Btn = (Button) findViewById(R.id.cancel_btn);
        Save_Btn = (Button) findViewById(R.id.save_btn);

        ET_Title = (EditText) findViewById(R.id.et_title);
        ET_Notes = (EditText) findViewById(R.id.et_notes);

        final NotesDbHelper Helper = new NotesDbHelper(AddNotes.this);

        Save_Btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (ET_Title.getText().toString().trim().equals("")) {

                    Toast.makeText(getApplicationContext(), "Title Required",
                            Toast.LENGTH_SHORT).show();

                } else if (ET_Notes.getText().toString().trim().equals("")) {

                    Toast.makeText(getApplicationContext(),
                            "Don't Forget To Type A Note", Toast.LENGTH_SHORT)
                            .show();

                } else {
                    boolean Added = true;
                    try {
                        String NoteTitle = ET_Title.getText().toString();
                        String NoteBody = ET_Notes.getText().toString();

                        Helper.Open();
                        Helper.AddNote(NoteTitle, NoteBody);

                    } catch (Exception e) {
                        Added = false;
                        e.printStackTrace();
                    }

                    finally {
                        if (Added) {

                            Toast toast = Toast.makeText(AddNotes.this, "Note Added Successfully", Toast.LENGTH_LONG);
                            toast.show();
                        }

                        Helper.Close();
                        ET_Title.setText("");
                        ET_Notes.setText("");
                    }
                }
            }
        });

        Cancel_Btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

Add Notes XML:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_title"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/et_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:ems="10"
        android:inputType="textCapWords" />

    <TextView
        android:id="@+id/tv_note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_note"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/et_notes"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_marginBottom="40dp"
        android:ems="10"
        android:inputType="textCapSentences|textMultiLine" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/cancel_btn"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="160dp"
            android:text="@string/cancel_note_btn" />

        <Button
            android:id="@+id/save_btn"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/save_note_btn" />
    </LinearLayout>

</LinearLayout>

Activity to UpdateNotes

    package example.mynotepad;

import example.mynotepad.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UpdateNotes extends Activity {

    NotesDbHelper nHelper;
    Button UpdateBtn, CancelBtn;
    EditText nTitle, nBody;

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

        UpdateBtn = (Button) findViewById(R.id.update_btn);
        CancelBtn = (Button) findViewById(R.id.Ucancel_btn);

        nTitle = (EditText) findViewById(R.id.Uet_title);
        nBody = (EditText) findViewById(R.id.Uet_notes);

        Intent intent = getIntent();
        Bundle mods = intent.getExtras();

        final int id = mods.getInt("id");
        String ntitle = mods.getString("ntitle");
        String nbody = mods.getString("nbody");

        nTitle.setText(ntitle);
        nBody.setText(nbody);

        UpdateBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                nHelper = new NotesDbHelper(UpdateNotes.this);
                nHelper.Open();

                String nt = nTitle.getText().toString();
                String nb = nBody.getText().toString();

                nHelper.Update(id, nt, nb);

                nHelper.Close();
                Intent display = new Intent(UpdateNotes.this,
                        MainActivity.class);
                setResult(RESULT_OK, display);
                finish();

                Toast.makeText(getApplicationContext(), "Update Successful",
                        Toast.LENGTH_SHORT).show();
            }
        });

        CancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(UpdateNotes.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }
}

NotesAdapter:

    package example.mynotepad;

import example.mynotepad.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class NotesAdapter extends CursorAdapter {

    public NotesAdapter(Context context, Cursor c) {
        super(context, c);
        // TODO Auto-generated constructor stub
    }

    public void bindView(View view, Context context, Cursor cursor) {

        TextView noteID = (TextView) view.findViewById(R.id.textView1);
        TextView noteTITLE = (TextView) view.findViewById(R.id.textView2);
        TextView noteBODY = (TextView) view.findViewById(R.id.textView3);

        noteID.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0))));
        noteTITLE.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
        noteBODY.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
    }

    @SuppressLint("InflateParams")
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View View = mInflater.inflate(R.layout.list, null);
        return View;
    }

    protected void onContentChanged() {
        // TODO Auto-generated method stub
        super.onContentChanged();
        notifyDataSetChanged();
    }

}

NotesDbHelper:

    package example.mynotepad;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class NotesDbHelper {

    public static final String DATABASE_NAME = "NotesDB.db";
    public static final int version = 1;

    public static final String Notes_Table = "Notes";

    public static final String Note_ID = "_id";
    public static final String NoteTitle = "NoteTitle";
    public static final String NoteBody = "NoteBody";

    private SQLiteDatabase nDatabase;
    public Context Context;

    public NotesDbHelper(Context c) {
        Context = c;
    }

    private class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, version);
        }

        @Override
        public void onCreate(SQLiteDatabase Database) {
            Database.execSQL("create table " + Notes_Table + " ( " + Note_ID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT , " + NoteTitle
                    + " TEXT NOT NULL ," + NoteBody + " TEXT NOT NULL);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }

    }

    public NotesDbHelper Open() throws SQLException {

        DatabaseHelper nDatabaseHelper = new DatabaseHelper(Context);
        nDatabase = nDatabaseHelper.getWritableDatabase();
        return this;
    }

    public void Close() {
        nDatabase.close();
    }

    public long AddNote(String noteTitle, String noteBody) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(NoteTitle, noteTitle);
        cv.put(NoteBody, noteBody);
        return nDatabase.insertOrThrow(Notes_Table, null, cv);
    }

    public Cursor AllData() {
        // TODO Auto-generated method stub
        String[] all = new String[] { Note_ID, NoteTitle, NoteBody };
        Cursor cursor = nDatabase.query(Notes_Table, all, null, null, null,
                null, null);
        return cursor;
    }

    public void Update(int id, String nt, String nb) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(NoteTitle, nt);
        cv.put(NoteBody, nb);

        nDatabase.update(Notes_Table, cv, Note_ID + " = " + id, null);
    }

    public void Delete(int i) {
        // TODO Auto-generated method stub
        nDatabase.delete(Notes_Table, Note_ID + " = " + i, null);
    }
}

This is the List XML:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20sp" />

</LinearLayout>

I have looked over my code several times and it looks fine. Probably it is something very simple that I cannot see, I don't know. Any help would really be appreciated. Thanks in advance.

user3830113
  • 123
  • 1
  • can you able to optimize the post, so any one can easily identify the problem – Sree Jul 29 '14 at 10:00
  • Try to fetch data in onResume() callback that is always called after onCreate() or when activity becomes active, where when you navigating back onCreate() may not be called – user3455363 Jul 29 '14 at 10:07

2 Answers2

0

please add

setResult(RESULT_OK, display);
finish();

in Save_Btn.setOnClickListener's onClick function

ie.

Save_Btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (ET_Title.getText().toString().trim().equals("")) {

                Toast.makeText(getApplicationContext(), "Title Required",
                        Toast.LENGTH_SHORT).show();

            } else if (ET_Notes.getText().toString().trim().equals("")) {

                Toast.makeText(getApplicationContext(),
                        "Don't Forget To Type A Note", Toast.LENGTH_SHORT)
                        .show();

            } else {
                boolean Added = true;
                try {
                    String NoteTitle = ET_Title.getText().toString();
                    String NoteBody = ET_Notes.getText().toString();

                    Helper.Open();
                    Helper.AddNote(NoteTitle, NoteBody);

                } catch (Exception e) {
                    Added = false;
                    e.printStackTrace();
                }

                finally {
                    if (Added) {

                        Toast toast = Toast.makeText(AddNotes.this, "Note Added Successfully", Toast.LENGTH_LONG);
                        toast.show();
                    }

                    Helper.Close();
                    ET_Title.setText("");
                    ET_Notes.setText("");
                }
               setResult(RESULT_OK, display);
               finish();   
            }
        }
    });
Sam
  • 4,046
  • 8
  • 31
  • 47
0

Because your data comes from DataBase and you populate list in onCreate() that is not necessarly called when you navigate back but is when you for example rotate screen. You should fetch data again for example in on Resume or in on Activity result and update adapter, passing new Cursor to use.

nListView = (ListView) findViewById(R.id.listView1);
    final NotesDbHelper nHelper = new NotesDbHelper(this);
    nHelper.Open();

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            nCursor = nHelper.AllData();
            nAdapter = new NotesAdapter(MainActivity.this, nCursor);
            nListView.setAdapter(nAdapter);
        }
    });

    nListView.setOnItemClickListener(this);
    nListView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View v,
                int position, long arg3) {
            // TODO Auto-generated method stub
            TextView id = (TextView) v.findViewById(R.id.textView1);
            final int i = Integer.parseInt(id.getText().toString());

            AlertDialog.Builder aDialog = new AlertDialog.Builder(
                    MainActivity.this);
            aDialog.setTitle("Delete Note?");
            aDialog.setMessage("This Will Delete It Permanently?");

            aDialog.setPositiveButton((getString(R.string.Delete)),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface Dialog,
                                int which) {
                            nHelper.Delete(i); // Delete Method in DBHelper
                            nCursor.requery();
                            nAdapter.notifyDataSetChanged();
                            nListView.setAdapter(nAdapter);
                        }
                    });
            aDialog.setNegativeButton((getString(R.string.Cancel)),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                        }
                    });
            aDialog.show();
            return false;
        }
    });


I think that putting this code into method lets call it for example: ListIni() should do the job and then you call it in your onCreate() and in onActivityResult() Basically it is about recreating your adapter object with new set of items in your case its Cursor.

Update
Create function private void AdapterIni() {

  nListView = (ListView) findViewById(R.id.listView1);

    final NotesDbHelper nHelper = new NotesDbHelper(this);
    nHelper.Open();

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            nCursor = nHelper.AllData();
            nAdapter = new NotesAdapter(MainActivity.this, nCursor);
            nListView.setAdapter(nAdapter);
        }
    });

    nListView.setOnItemClickListener(this);
    nListView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View v,
                int position, long arg3) {
            // TODO Auto-generated method stub
            TextView id = (TextView) v.findViewById(R.id.textView1);
            final int i = Integer.parseInt(id.getText().toString());

            AlertDialog.Builder aDialog = new AlertDialog.Builder(
                    MainActivity.this);
            aDialog.setTitle("Delete Note?");
            aDialog.setMessage("This Will Delete It Permanently?");

            aDialog.setPositiveButton((getString(R.string.Delete)),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface Dialog,
                                int which) {
                            nHelper.Delete(i); // Delete Method in DBHelper
                            nCursor.requery();
                            nAdapter.notifyDataSetChanged();
                            nListView.setAdapter(nAdapter);
                        }
                    });
            aDialog.setNegativeButton((getString(R.string.Cancel)),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                        }
                    });
            aDialog.show();
            return false;
        }
    });`

And then replace it so you wont be calling same code twice in MainActivity onCreate()
Then in your MainActivity onActivityResult function call your AdapterIni() method.

user3455363
  • 408
  • 1
  • 5
  • 13
  • To get items for listView in android most commonly used approach is to use Adapter in your case its NotesAdapter that extends CursoAdapter. CursorAdapter accepts Cursor object as dataSource for your list. When you first start application your `onCreate()` method fires what happens is you taking data from dataBase using NotesDbHelper class by calling AllData() method that returns Cursor object. Cursor is Object that stores values from dataBase, But since your data changed in DataBase you need to provide Adapter with new set of data. Thats why you need to Create Adapter again. – user3455363 Jul 29 '14 at 10:51
  • Your code I just copied should work if you put it to seperate method, so you can use it in onActivityResult(). – user3455363 Jul 29 '14 at 11:09
  • In main Activity you already have onActivityResult() btw its set to do something when result code is 101, so when you finishing Update activity – user3455363 Jul 29 '14 at 11:19
  • I have tried doing it but with no luck..could you please provide code for this answer..would be really appreciated.thanks – user3830113 Jul 30 '14 at 15:48