zhacHaven 0 Newbie Poster
Good day to all ..i need help with this..i want to delete and edit the selected row from a listView with the use of alert dialog.i have a bit knowledge of constructing an alert dialog in my class..the problem is the method to call for deleting and editing from my helper class and how am i going to implement it in my Activity
Thank You in Advance..this is my last option after searching and relating to other problems that until now i still scratching Google
this is my HELPER CLASS everything works fine with this
public class DatabaseHelper extends SQLiteOpenHelper{
    public static final String ITEM_ID = "myid";
    public static final String LOCATION = "location";
    public static final String DESCRIPTION = "description";
    public static final String CATEGORY = "category";
    public static final String MONTHONE ="monthOne";
    public static final String REMIND_AT ="remindAt";
    public static final String QTY ="quantity";
    public static final String TABLE_NAME ="add_new";
   // private static final String COLUMN_NAME="ageing_column";
   // SQLiteDatabase sqLiteDatabase;
    private static final String DATABASE_NAME=" EXPIRATIONMONITORING.DB";
    private static final int DATABASE_VERSION = 1;
    private static  final String CREATE_QUERY =
            "CREATE TABLE add_new (myid  INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT,  category TEXT, monthOne TEXT, remindAt TEXT, quantity TEXT, location TEXT )";

private SQLiteDatabase sqLiteDatabase;
 DatabaseHelper databaseHelper;
    public DatabaseHelper(Context context)
    {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        //this.context1=context;
        Log.e("DATABASE OPERATIONS", "Database created / opened....");
    }
    @Override
    public void onCreate(SQLiteDatabase db) {


        db.execSQL(CREATE_QUERY);

        Log.e("DATABASE OPERATIONS", "Table created....");

    }
    public void openDB() throws SQLiteException {
        sqLiteDatabase = databaseHelper.getWritableDatabase();
    }
    public void closeDB(){
        databaseHelper.close();
    }

    public void addInformations(String description, String category, String monthOne,String quantity,String remind, String location, SQLiteDatabase db)
    {
        ContentValues contentValues=new ContentValues();
        contentValues.put(LOCATION,location);
        contentValues.put(DESCRIPTION,description);
        contentValues.put(CATEGORY,category);
        contentValues.put(MONTHONE,monthOne);
        contentValues.put(REMIND_AT,remind);
        contentValues.put(QTY,quantity);
        db.insert(TABLE_NAME, null, contentValues);
        Log.e("DATABASE OPERATIONS", "One row inserted");
        db.close();
    }

    public Cursor getInformations(SQLiteDatabase db)
    {
        Cursor cursor;
        String[] projections ={DESCRIPTION,CATEGORY,MONTHONE, QTY, REMIND_AT,LOCATION};
        cursor=db.query(TABLE_NAME, projections, null, null, null, null, null);
        return cursor;
    }
    public Cursor getContact(String location,SQLiteDatabase sqLiteDatabase)
    {
        String[] projections ={DESCRIPTION,CATEGORY,MONTHONE,QTY, REMIND_AT,LOCATION};
        String selection = LOCATION+" LIKE? ";
        String [] sargs={location};
        Cursor cursor=sqLiteDatabase.query(TABLE_NAME,projections,selection,sargs,null,null,null);
        return  cursor;
    }
    //For AutoCompleteTextView searching
    public String[] SelectAllData()
    {
        try
        {
            String arrData[]=null;
            SQLiteDatabase db;
            db=this.getReadableDatabase();
            String strSQL=" SELECT "+LOCATION+" FROM "+TABLE_NAME;
            Cursor cursor =db.rawQuery(strSQL,null);
            if(cursor !=null)
            {
                if(cursor.moveToFirst())
                {
                    arrData=new String[cursor.getCount()];
                    int i=0;
                    do
                    {
                        arrData[i]=cursor.getString(0);
                        i++;

                    }while(cursor.moveToNext());
                }
            }
            cursor.close();
            return arrData;

        }catch(Exception e){
            return null;
        }
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}
This is my Main activity..this is where all the items that was inserted to sqlite database is viewed through my listview
public class ViewListsActivity extends AppCompatActivity {
    DatabaseHelper databaseHelper=null;
    SQLiteDatabase sqLiteDatabase ;
    ListDataAdapter listDataAdapter ;
    ListView listView;
    Cursor cursor=null ;
    EditText delete_txt = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.view_lists_activity);
            listView = (ListView) findViewById(R.id.search_listView);
            delete_txt = (EditText) findViewById(R.id.delete_text);
            listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
            databaseHelper = new DatabaseHelper(getApplicationContext());
            sqLiteDatabase = databaseHelper.getReadableDatabase();
            cursor = databaseHelper.getInformations(sqLiteDatabase);
            listView.setAdapter(listDataAdapter);
            if (cursor.moveToFirst()) {
                do {
                    String description, category, month1, remind, qty, location;
                    description = cursor.getString(0);
                    category = cursor.getString(1);
                    month1 = cursor.getString(2);
                    qty = cursor.getString(3);
                    remind = cursor.getString(4);
                    location = cursor.getString(5);
                    DataProvider dataProvider = new DataProvider(description, category, month1, qty, remind, location);
                    listDataAdapter.add(dataProvider);
                } while (cursor.moveToNext());
            }
    }
    public void ToSearchBtn(View view) {
        Intent intent = new Intent(this, ThirdActivitySearchAllData.class);
        startActivity(intent);
    }
    public void ToAddNewItemBtn(View view) {
        Intent intent = new Intent(this, SecondActivitySaveData.class);
        startActivity(intent);
    }
}
this my Adapter just in case you need to see it
public class ListDataAdapter extends ArrayAdapter  {
    List list = new ArrayList();

    public ListDataAdapter(Context context, int resource) {
        super(context, resource);
    }



    static class LayoutHandler
    {
        TextView DESCRIPTION,CATEGORY,MONTH1,QTY,REMIND,LOCATION;
    }
    public void add(Object object)
    {
        super.add(object);
        list.add(object);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row =convertView;
        LayoutHandler layoutHandler;

        if(row==null)
        {
            LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row=layoutInflater.inflate(R.layout.row_layout,parent,false);
            layoutHandler=new LayoutHandler();

            layoutHandler.DESCRIPTION= (TextView) row.findViewById(R.id.text_description);
            layoutHandler.CATEGORY= (TextView) row.findViewById(R.id.text_category);
            layoutHandler.MONTH1= (TextView) row.findViewById(R.id.text_monthOne);
            layoutHandler.REMIND= (TextView) row.findViewById(R.id.text_remind);
            layoutHandler.QTY= (TextView) row.findViewById(R.id.text_qty);
            layoutHandler.LOCATION= (TextView) row.findViewById(R.id.text_location);
            row.setTag(layoutHandler);
        }else
        {
            layoutHandler=(LayoutHandler)row.getTag();

        }
        DataProvider dataProvider= (DataProvider) this.getItem(position);
        layoutHandler.DESCRIPTION.setText(dataProvider.getDescription());
        layoutHandler.CATEGORY.setText(dataProvider.getCategory());
        layoutHandler.MONTH1.setText(dataProvider.getMonthOne());
        layoutHandler.REMIND.setText(dataProvider.getRemindAt());
        layoutHandler.QTY.setText(dataProvider.getQuantity());
         layoutHandler.LOCATION.setText(dataProvider.getLocation());


        return row;
    }


}

Dani AI

Generated

: short, practical approach and a few gotchas found in the posted helper/activity.

Add two small methods to the SQLiteOpenHelper: one to delete by primary key and one to update by primary key. Ensure the query that populates the ListView includes the primary-key column so each DataProvider carries the row id. Show a context menu (or an AlertDialog on long-press) that offers Edit/Delete; call the helper methods from the dialog handlers and then remove or refresh the adapter. The helper should call getWritableDatabase() on itself (not on an uninitialized field) — the posted openDB() looks like a likely bug.

Example helper methods (add to the SQLiteOpenHelper subclass):

public boolean deleteRow(long id) {
    SQLiteDatabase db = getWritableDatabase();
    int deleted = db.delete("add_new", "myid = ?", new String[]{ String.valueOf(id) });
    db.close();
    return deleted > 0;
}

public boolean updateRow(long id, ContentValues values) {
    SQLiteDatabase db = getWritableDatabase();
    int updated = db.update("add_new", values, "myid = ?", new String[]{ String.valueOf(id) });
    db.close();
    return updated > 0;
}

Example Activity flow (long-press -> dialog -> action):

listView.setOnItemLongClickListener((parent, view, position, id) -> {
    long rowId = ((DataProvider) adapter.getItem(position)).getId();
    new AlertDialog.Builder(this)
      .setItems(new String[]{"Edit","Delete"}, (d, which) -> {
         if (which == 1) {
           if (dbHelper.deleteRow(rowId)) {
             adapter.remove(adapter.getItem(position));
             adapter.notifyDataSetChanged();
           }
         } else {
           startActivity(new Intent(this, EditActivity.class).putExtra("row_id", rowId));
         }
      }).show();
    return true;
});

Troubleshooting notes: include the id in the cursor projection and DataProvider, close cursors, call notifyDataSetChanged or reload the cursor after DB changes, and avoid calling DB helper methods on an uninitialized helper instance. For dialogs see the Android guide on dialogs and for delete/update see the SQLiteDatabase API: Dialogs guide and SQLiteDatabase reference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.