javaandroidsqlitelistviewlong-click

Remove by longclick on row from ListView (SQLite database)


I Try for long hours to delete a row from a listview (SQLite).

What I was able to do until now ?

  1. Showing all the data by rows on the listview.
  2. Long click on one of the rows showing a menu (delete or update).

What I could not do until now ?

  1. Taking the id from the row if I long click on it.

** The delete and update process I try to finish later, I just need now to take the id of the row I clicked.

I've included the relevant files and a prtscrn after long click on row

DataListActivity.java -- ** The most relevant file **

package com.example.ido.grades;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class DataListActivity extends ActionBarActivity {
    ListView listView;
    SQLiteDatabase sqLiteDatabase;
    CourseDbHelper courseDbHelper;
    Cursor cursor;
    ListDataAdaptar listDataAdaptar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.data_list_layout);
        listView = (ListView) findViewById(R.id.list_view);
        listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
        listView.setAdapter(listDataAdaptar);
        registerForContextMenu(listView);
        courseDbHelper = new CourseDbHelper(getApplicationContext());
        sqLiteDatabase = courseDbHelper.getReadableDatabase();
        cursor = courseDbHelper.getInformation(sqLiteDatabase);
        registerForContextMenu(listView);
        if (!cursor.moveToFirst()){
        }
        else {
            do {
                String year,semester,course,points,grade;
                year = cursor.getString(0);
                semester = cursor.getString(1);
                course = cursor.getString(2);
                points = cursor.getString(3);
                grade = cursor.getString(4);
                DataProvider dataProvider  = new DataProvider(year,semester,course,points,grade);
                listDataAdaptar.add(dataProvider);
            }
            while (cursor.moveToNext());
        }
    }
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_data_list, menu);

    }
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.update_item:
                Toast.makeText(this,"update",Toast.LENGTH_LONG).show();
                return true;
            case R.id.delete_item:
                Toast.makeText(this,"delete",Toast.LENGTH_LONG).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    }

data_list_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    tools:context="com.example.ido.grades.DataListActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view"
        ></ListView>


</RelativeLayout>

ListDataAdapter.java

  package com.example.ido.grades; 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class ListDataAdaptar extends ArrayAdapter{
        List list = new ArrayList();
    public ListDataAdaptar(Context context, int resource) {
        super(context, resource);
    }

    static class LayoutHandler{
        TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
    }
    @Override
    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.YEAR = (TextView)row.findViewById(R.id.textYear);
            layoutHandler.SEMESTER = (TextView)row.findViewById(R.id.textSemester);
            layoutHandler.COURSE = (TextView)row.findViewById(R.id.textCourse);
            layoutHandler.POINTS = (TextView)row.findViewById(R.id.textPoints);
            layoutHandler.GRADE = (TextView)row.findViewById(R.id.textGrade);
            row.setTag(layoutHandler);
        }
        else{
            layoutHandler = (LayoutHandler) row.getTag();

        }
        DataProvider dataProvider = (DataProvider) this.getItem(position);
        layoutHandler.YEAR.setText(dataProvider.getYear());
        layoutHandler.SEMESTER.setText(dataProvider.getSemester());
        layoutHandler.COURSE.setText(dataProvider.getCourse());
        layoutHandler.POINTS.setText(dataProvider.getPoints());
        layoutHandler.GRADE.setText(dataProvider.getGrade());
        return row;
    }
}

After long click

CourseDbHelper.java

 package com.example.ido.grades;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

    public class CourseDbHelper extends SQLiteOpenHelper {

        private static final String DATABASE_NAME  = "COURSEINFO.DB";
        private static final int DATABASE_VERSION = 1;


        public String CREATE_QUERY = "CREATE TABLE " + UserCourse.NewCourseInfo.TABLE_NAME + "("+ UserCourse.NewCourseInfo.YEAR+" TEXT,"
                + UserCourse.NewCourseInfo.SEMESTER+" TEXT,"+ UserCourse.NewCourseInfo.COURSE+" TEXT,"+ UserCourse.NewCourseInfo.POINTS+" TEXT,"
                + UserCourse.NewCourseInfo.GRADE+" TEXT);";

        public  CourseDbHelper (Context context){

            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            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 putInformation(String year, String semester, String course, String points,String grade,SQLiteDatabase db){
            ContentValues cv = new ContentValues();
            cv.put(UserCourse.NewCourseInfo.YEAR, year);
            cv.put(UserCourse.NewCourseInfo.SEMESTER, semester);
            cv.put(UserCourse.NewCourseInfo.COURSE, course);
            cv.put(UserCourse.NewCourseInfo.POINTS,points);
            cv.put(UserCourse.NewCourseInfo.GRADE, grade);
            db.insert(UserCourse.NewCourseInfo.TABLE_NAME, null, cv);
            Log.e("DATABASE_OPERATIONS", "One raw inserted");

        }

        public Cursor getInformation(SQLiteDatabase db){
            Cursor cursor;
            String[] projections = {UserCourse.NewCourseInfo.YEAR,UserCourse.NewCourseInfo.SEMESTER,
                    UserCourse.NewCourseInfo.COURSE, UserCourse.NewCourseInfo.POINTS,UserCourse.NewCourseInfo.GRADE};
              cursor=     db.query(UserCourse.NewCourseInfo.TABLE_NAME,projections,null,null,null,null,null );
            return cursor;
        }
        public void deleteInformation(String  id){

        }

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

        }

    }

Solution

  • To get the index of the selected row, add the following code to 'onContextItemSelected(MenuItem item)':

       AdapterContextMenuInfo info = 
                   (AdapterContextMenuInfo) item.getMenuInfo();`
       int mySelectedRowIndex = info.position;
    

    With the following statement you get the ListView data in the selected row:

    (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
    

    There is no id (= database primary key) and so you can only delete every row from table 'UserCourse.NewCourseInfo.TABLE_NAME' which matches the values in the selected ListView row.

    (I don't know how much you know about SQL - so be warned: if a row's values match the input values the row will be deleted! If you want to delete just one row maybe you should include a primary key for the table ).

    So you have to change the 'deleteInformation()' method:

    public void deleteInformation(String  year, String semester, 
                String grade, String course, String points){
        SQLiteDatabase db = null;
        try
        {
             db = this.getWritableDatabase();
    
             String where = UserCourse.NewCourseInfo.YEAR + " = ? AND "
                      + UserCourse.NewCourseInfo.SEMESTER + " = ? AND "
                      + UserCourse.NewCourseInfo.COURSE + " = ? AND "
                      + UserCourse.NewCourseInfo.POINTS + " = ? AND "
                      + UserCourse.NewCourseInfo.GRADE + " = ?";
    
             int iNumberDeleted = db.delete(
                                   UserCourse.NewCourseInfo.TABLE_NAME, 
                                   where,
                          new String[]{year, semester, course, points, grade}
                                   );
            // you might want to evaluate the number of affected rows
        }
        catch (Exception ex)
        {
            Log.d("DB_DELETE", "...your data..." + "\n" + ex.getMessage());
    
        }
        finally
        {
            if (db != null)
                db.close();
        }
    
    
    
    }