1

I'm new to android and I got a problem with refreshing my listview after deleting items from it. I've tried everything and cant get it to work so I'm asking for help. I know that I gotta use notifyDataSetChanged on my adapter but I just have no clue where to put it. Thanks in advance guys. Whole project uploaded on zippyshare:http://www6.zippyshare.com/v/TZVGTFJp/file.html

public class MainActivity extends AppCompatActivity {


DBHandler handler;
Context context = this;
ListView listView;
ArrayAdapter arrayAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    EditText etName = (EditText) findViewById(R.id.etNameID);
    EditText etPhone = (EditText) findViewById(R.id.etPhoneID);


    handler = new DBHandler(this);

    printDatabase();


    if (listView != null) {
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, final long id) {

                PopupMenu popup = new PopupMenu(context, view);
                popup.getMenuInflater().inflate(R.menu.menu_delete_popup, popup.getMenu());
                popup.show();

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        switch (item.getItemId()) {

                            case R.id.deleteItemID:

                                handler.deleteContact(id);

                                printDatabase();


                                break;


                        }


                        return true;
                    }
                });


                return true;
            }
        });
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if (id == R.id.addContactID) {

        openAddDialog();


    }

    return super.onOptionsItemSelected(item);
}

public void printDatabase() {


    ArrayList array_list = handler.getAllCotacts();
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(arrayAdapter);


}

public void openAddDialog() {

    android.app.AlertDialog.Builder makeDialog = new android.app.AlertDialog.Builder(this);
    LayoutInflater li = getLayoutInflater();
    View v = li.inflate(R.layout.contacts_add_dialog, null);
    makeDialog.setView(v);

    //tu idu varijable

    final EditText etName = (EditText) v.findViewById(R.id.etNameID);
    final EditText etPhone = (EditText) v.findViewById(R.id.etPhoneID);

    makeDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            String textFromEtName = etName.getText().toString();
            String textFromEtPhone = etPhone.getText().toString();

            handler.insertContact(textFromEtName, textFromEtPhone);

            printDatabase();


        }
    });

    makeDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    android.app.AlertDialog ad = makeDialog.create();
    ad.show();


}

}

Here is the DBHandler code:

public class DBHandler extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_PHONE = "phone";


public DBHandler(Context context)
{
    super(context, DATABASE_NAME , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(
            "CREATE TABLE contacts " +
                    "(id INTEGER PRIMARY KEY, name TEXT,phone TEXT,email TEXT, street TEXT,place TEXT)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS contacts");
    onCreate(db);
}

public boolean insertContact  (String name, String phone)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", name);
    contentValues.put("phone", phone);
    db.insert("contacts", null, contentValues);
    return true;
}

public Cursor getData(int id){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
    return res;
}

public int numberOfRows(){
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
    return numRows;
}

public boolean updateContact (Integer id, String name, String phone)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", name);
    contentValues.put("phone", phone);
    db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
    return true;
}


public void deleteContact(long id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_ID + " = ?",
            new String[] { String.valueOf(id) });
    db.close();
}
public ArrayList<String> getAllCotacts()
{
    ArrayList<String> array_list = new ArrayList<String>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
        res.moveToNext();
    }
    return array_list;
}

}

Nenco
  • 241
  • 4
  • 13
  • 1
    Try `arrayAdapter.notifyDataSetChanged()` immediate after you perform `Delete` with database. – Jay Rathod Apr 16 '16 at 18:34
  • I think this link will help you: http://stackoverflow.com/questions/14503006/android-listview-not-refreshing-after-notifydatasetchanged – xiaoyaoworm Apr 16 '16 at 18:36

3 Answers3

0

Update your printDatabase Function like below :

public void printDatabase() {


ArrayList array_list = handler.getAllCotacts();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,    
 array_list);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged(); 
listView.invalidateViews();
}
Ashish Shukla
  • 1,027
  • 16
  • 36
  • Ashish Shukla still doesnt refresh it – Nenco Apr 16 '16 at 18:47
  • are you sure your data is getting deleted from database? – Ashish Shukla Apr 16 '16 at 18:50
  • ye I'm sure cause it deletes it but not immediately. – Nenco Apr 16 '16 at 18:53
  • `public void deleteContact(long id){ SQLiteDatabase db=getWritableDatabase(); String string =String.valueOf(id); db.execSQL("DELETE FROM contacts WHERE id = '" + string + "'"); }` – Nenco Apr 16 '16 at 18:54
  • @Nenco Have you checked into the database that item got affects and deleted with whatever id is, – Jay Rathod Apr 16 '16 at 19:06
  • jay I didnt use mozilla firefox's sql lite add on. I updated the topic with DBHandler code so you can check if there is something wrong but it shouldnt be – Nenco Apr 16 '16 at 19:19
  • Ashish Shukla tried it still doesnt work I will upload the whole project on zippyshare in 5min just so its easier for you guys – Nenco Apr 16 '16 at 19:50
0

after removing an element made ​​another called from the function retrieve the results from the database

  • dont get your answer really. You mean that I should getAllContacts after deleting one item? cause I'm already doing that – Nenco Apr 16 '16 at 19:54
0

Here you are adding an item using index number of row

array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));

And here you are trying to delete a row using index number of view object in a listview

handler.deleteContact(id);

so instead of using CONTACTS_COLUMN_NAME you have to use CONTACTS_COLUMN_ID

array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_ID)));

even if you do so it may not work because you can not guarantee that number of a view in Listview match with id in the table. id number might be 99 and view number always start with 0.

Here is a primitive solution step 1

public ArrayList<HashMap<String, String>> getAllCotacts()
{
    ArrayList<HashMap<String, String>> array_list = new ArrayList<String>();
.
.
.
int counter = 0;
 while(res.isAfterLast() == false){
        HashMap<String, String> contact = new HashMap<String, String>();
        contactMap.put("index",res.getString(res.getColumnIndex(CONTACTS_COLUMN_ID));
        contactMap.put("name",res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
        array_list.add(contact);
        res.moveToNext();
    }

step 2 make it global

HashMap array_list

step 3

handler.deleteContact(array_list.get(id).get("index"));

Most importantly this is a primitive solution and I think writing your own adapter is the best solution.

Burak Karasoy
  • 1,682
  • 2
  • 21
  • 33