I have created a list view. On button click the data is added in list and also stored in an SQLite database. I have also added the image on the right-hand side of list, on click of which a particular row data is deleted, but I also want to delete data from SQLite. How could I do this?
Main Activity.Java
public class MainActivity extends Activity {
EditText editText;
Button Button,Button1;
ListView listView;
ArrayList<String> listItems;
BaseAdapter adapter;
private DataBaseHandler mHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DataBaseHandler(this);
editText = (EditText) findViewById(R.id.editText);
Button = (Button) findViewById(R.id.Button);
listView = (ListView) findViewById(R.id.listview);
listItems = new ArrayList<String>();
adapter =new BaseAdapter()
{
#Override
public View getView(final int arg0, View arg1, ViewGroup arg2)
{
LayoutInflater inflater = getLayoutInflater();
arg1 = inflater.inflate(R.layout.custom, null);
TextView textview = (TextView)arg1. findViewById(R.id.textView1);
textview.setText(listItems.get(arg0));
ImageView image = (ImageView)arg1. findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
listItems.remove(arg0);
listView.setAdapter(adapter);
Toast.makeText(MainActivity.this, "Item has been successfully deleted", Toast.LENGTH_LONG)
.show();
}
});
return arg1;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public int getCount() {
//code to set the list item size according to array data size
return listItems.size();
}
};
listView.setAdapter(adapter);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
listItems= mHelper.addListItem(editText.getText().toString());
adapter.notifyDataSetChanged();
listView.setSelection(listView.getAdapter().getCount()-1);
editText.getText().clear();
}
});
}
}
DATABASE HANDLER.JAVA
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDatabase.db";
private static final String TABLE_LIST = "MyListItem";
private static final String KEY_ID = "id";
private static final String KEY_ListItem = "listitem";
public static final String KEY_NAME = null;
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_LIST_TABLE = "CREATE TABLE " + TABLE_LIST + "(" + KEY_ID
+ " integer primary key autoincrement," + KEY_ListItem + " TEXT" + ")";
db.execSQL(CREATE_LIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);
onCreate(db);
}
ArrayList<String> addListItem(String listItem)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ListItem, listItem);
db.insert(TABLE_LIST, null, values);
ArrayList<String> items=new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LIST;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
items.add(cursor.getString(1));
cursor.moveToNext();
}
cursor.close();
db.close();
return items;
}
Cursor getListItem()
{
String selectQuery = "SELECT * FROM " + TABLE_LIST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
}
To delete single data entry(i.e. Row) make a method in database handler:
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + "=?",
new String[] { String.valueOf(id) }); // KEY_ID= id of row and third parameter is argument.
db.close();
}
This method will delete single row which ID is given.
You will need to make a method deleteItem in your DataBaseHandler class. Which will do something like,
db.delete(TABLE_LIST , KEY_ID + "=" + yourIdToBeDeleted, null);
And make a call to this method from your delete button/image's onClick as:
mHelper.deleteItem(idOfItemToBeDeleted);
Hope it helps.
Related
I am having a lot of trouble finding out how to delete data from my sqlite database by using ID.
How do I delete data from my sqlite databse by using ID?
final ItemTouchHelper.SimpleCallback itemTouchHelper = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
list.remove(viewHolder.getAdapterPosition());
adapter.notifyDataSetChanged();
/////// I want to delete this data from my sqlite Data Base by using it's id. But how do I get the id?///////
}
};
Should that be done in the OnBindViewHolder?
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.notePadTextView.setText(arrayListNote.get(position).getNote());
}
This is my custom adapter:
public class NotesCustomAdapter extends RecyclerView.Adapter{
private ArrayList arrayListNote;
private Context context;
public NotesCustomAdapter(ArrayList<newNote> arrayListNote, Context context) {
this.arrayListNote = arrayListNote;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notepad_model,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.notePadTextView.setText(arrayListNote.get(position).getNote());
}
#Override
public int getItemCount() {
return arrayListNote.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
LinearLayout NotePadMode;
TextView notePadTextView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
NotePadMode= itemView.findViewById(R.id.NotePadModel);
notePadTextView = itemView.findViewById(R.id.notePadTextView);
}
}
}
This is my SQlite Database:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DATABSE_NAME = "AllWorkHours.db";
public static final String TABLE_NAME = "ALLWORKHOURS";
public static final String COL_0 = "ID";
public static final String COL_1 = "DATE";
public static final String COL_2 = "TIMESHIFTSTART";
public static final String COL_3 = "TIMESHIFTENDS";
public static final String COL_4 = "NOTES";
public static final String COL_5 = "NOTEMEMOS";
public static final int DATABASE_Version = 5;
public DataBaseHelper(Context context) {
super(context, DATABSE_NAME,null,DATABASE_Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE TEXT, TIMESHIFTSTART INTEGER, TIMESHIFTENDS TEXT, NOTES TEXT, NOTEMEMOS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS ALLWORKHOURS");
onCreate(db);
}
public boolean addHours(String Date, String TimeShiftStart, String TimeShiftEnds, String Notes){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, Date);
contentValues.put(COL_2, TimeShiftStart);
contentValues.put(COL_3, TimeShiftEnds);
contentValues.put(COL_4, Notes);
long inserted = db.insert(TABLE_NAME,null,contentValues);
if (inserted == -1){
return false;
}else{
return true;
}
}
public ArrayList<newShift> viewAllHours(){
ArrayList<newShift> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String Date = cursor.getString(1);
String timestart = cursor.getString(2);
String timeEnds = cursor.getString(3);
String notes = cursor.getString(4);
newShift newShift = new newShift(id,Date,timestart,timeEnds,notes);
arrayList.add(newShift);
}
return arrayList;
}
public boolean addNotes(String NOTEMEMOS) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_5, NOTEMEMOS);
long inserted = db.insert(TABLE_NAME, null, contentValues);
if (inserted == -1){
return false;
}else{
return true;
}
}
public ArrayList<newNote> ViewAllNotes() {
ArrayList<newNote> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT NOTEMEMOS FROM " + TABLE_NAME, null);
while(cursor.moveToNext()){
String notes = cursor.getString(0);
newNote newnote = new newNote(notes);
arrayList.add(newnote);
}
return arrayList;
}
}
You can try this
db.delete(table, whereClause, whereArgs)
after delete entry, refresh your view (listview)
You have to get Id of your model before remove like:
newShift obj = list.get(viewHolder.getAdapterPosition());
DataBaseHelper _yourdatabaseObject = youtDatabaseInstance();
_yourdatabaseObject.removeDataByID(""+obj.id);
list.remove(viewHolder.getAdapterPosition());
adapter.notifyDataSetChanged();
Make A function Of delete note in DataBaseHelper.
public void deleteMyNote(String id){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ TABLE_NAME +" where ID='"+ id +"'");
}
I'm making a database on SQLite, but have a error with adding it in Main Activity. I'm sure I made all right in building database.
Tried to change on activity name - nothing changed. Tried change on getActivity() - got a new error.
Code from Main activity (part with error):
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
dbHelper = new DBHelper(this);
}
...
Database code (called DBHelper in my project):
package com.gov.work;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "contactDb";
public static final String TABLE_CONTACTS = "contacts";
public static final String KEY_ID = "_id";
public static final String KEY_MAIL = "mail";
public static final String KEY_PASSWORD = "password";
public DBHelper(Context context, String name, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_CONTACTS + "(" + KEY_ID + " integer primary key,"+ KEY_MAIL + " text," + KEY_PASSWORD + " text" + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_CONTACTS);
onCreate(db);
}
}
When I try to run project it gives me compilation error.
It's because you're trying to instantiate your DBHelper with:
dbHelper = new DBHelper(this);
but you didn't have a matching constructor in your DBHelper. You only have the following constructor:
public DBHelper(Context context, String name, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
So, you need to add a constructor to DBHelper with Context as its only parameter to solve your problem, like this:
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
You can use getActivity() instead this
dbHelper = new DBHelper(this);
to
dbHelper = new DBHelper(getActivity());
I have a bug in my code. Whenever I delete items from my SQ Lite database, the itens are deleted. Although, when I insert a new item, the items who were removed appear again. Can you help me? Sorry to bother, but i don't know what to do.
Here it is my MainActivity.
MainActivity.java
public class MainActivity extends Activity
{
private InputDbHelper mHelper;
private ListView mListView;
private EditText mEditText;
private Button mButton;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mListView=(ListView)findViewById(R.id.listView);
mListView.setAdapter(adapter);
mHelper = new InputDbHelper(this);
updateUI();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, input);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
list.remove(positionToRemove);
adapter.remove(String.valueOf(positionToRemove));
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<String>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (adapter== null) {
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,
taskList);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(taskList);
adapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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;
}
return super.onOptionsItemSelected(item);
}
}
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.example.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
My Database:
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
By doing this:
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry._ID + " = ?", new String[] {
String.valueOf(positionToRemove)
}
);
you're coding it to use the position of the ListView item as a table ID, which it may work for the first rows when you create a new table, but when you'll start deleting items all things will get messed up.
You'll have to store the ID's either by creating a custom class for ArrayAdapter or by storing row ID to an Array/List and use positionToRemove to get the ID from that List, but that it can result to unexpected behaviur if you mess with the ListView and don't update the List data.
Check this question Custom Adapter for List View to see how you can create a custom adapter and save row ID to all ListView items along with the text.
Sorry for my English. I am new in Android Development. I have an app in which the user make notes. When the user make his note, the note is saved in a SQ Lite Database and is shown in a ListView. When I want to delete the note, the note is removed from the ListView but not from the Database. Could you help me?
MainActivity.java
public class MainActivity extends Activity
{
private InputDbHelper mHelper;
private ListView mListView;
private EditText mEditText;
private Button mButton;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mListView=(ListView)findViewById(R.id.listView);
mListView.setAdapter(adapter);
mHelper = new InputDbHelper(this);
updateUI();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, input);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
deleteTask();
adb.show();
}
});
}
public void deleteTask() {
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<String>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (adapter== null) {
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,
taskList);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(taskList);
adapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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;
}
return super.onOptionsItemSelected(item);
}
}
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.example.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
You are not deleting the row in your database.You can do this
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
list.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
deleteTask();
adb.show();
}
});
try something like:
db.execSQL("DELETE FROM myTable WHERE noteID = 7")
Or more generally:
`int idToDelete = 7; //for example
db.execSQL(
"DELETE FROM "+ InputContract.TaskEntry.TABLE +
" WHERE "+ InputContract.TaskEntry._ID +" = " + idToDelete
)`
How to access data after clicking an Item of RecyclerView. What I need is the logic behind on how to get the expanded Items from the database.
Currently for adapter using CursorRecyclerViewAdapter to get data from database https://gist.github.com/skyfishjy/443b7448f59be978bc59
RemindersAdapter.java
public class RemindersAdapter extends CursorRecyclerViewAdapter<RemindersAdapter.ItemViewHolder> {
private final LayoutInflater inflater;
List<ListInfo> data = Collections.emptyList();
private Context context;
ListInfo temporaryBucket;
public RemindersAdapter(Context context, Cursor cursor){
super(context, cursor);
inflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.reminder_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
temporaryBucket = new ListInfo();
return holder;
}
#Override
public void onBindViewHolder(ItemViewHolder viewHolder, Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(MyDBHandler.COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_TITLE_REMINDER));
String desc = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DESC_REMINDER));
String date = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DATE_REMINDER));
viewHolder.title.setText(title);
}
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
public ItemViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.reminderTitle);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
}
}
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "paroah.db";
public static final String TABLE_REMINDER = "reminders";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE_REMINDER = "title";
public static final String COLUMN_DESC_REMINDER = "desc";
public static final String COLUMN_DATE_REMINDER = "date_created";
private Cursor allReminders;
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = " CREATE TABLE "
+TABLE_REMINDER+ "(" +
COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_TITLE_REMINDER + " TEXT ,"+
COLUMN_DESC_REMINDER + " TEXT ,"+
COLUMN_DATE_REMINDER + " TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("aoi", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
try {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_REMINDER);
onCreate(db);
} catch (SQLException e) {
Log.d("aoi", "getting exception "
+ e.getLocalizedMessage().toString());
}
}
public void addReminder(ListInfo reminder ){
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE_REMINDER, reminder.getTitle());
values.put(COLUMN_DESC_REMINDER, reminder.getDesc());
values.put(COLUMN_DATE_REMINDER, reminder.getDate());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_REMINDER, null, values);
db.close();
}
public Cursor getAllReminders() {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+TABLE_REMINDER;
allReminders = db.rawQuery(query, null);
return allReminders;
}
}
In my onBindViewHolder I'm getting "id, title, desc and date" but only showing the title which when clicked will show the desc and date. For testing just showing a Toast for now on click of item.
You can set the onClickListener in onBindViewHolder() with holder.itemView.setOnClickListener(new OnClickListener({...}), and you can access all data you need.
You can bind view holder with all the data even if you just show the title
#Override
public void onBindViewHolder(ItemViewHolder viewHolder, Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(MyDBHandler.COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_TITLE_REMINDER));
String desc = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DESC_REMINDER));
String date = cursor.getString(cursor.getColumnIndex(MyDBHandler.COLUMN_DATE_REMINDER));
viewHolder.bind(id, title, desc, date);
}
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
int idData;
String titleData;
String descData;
String dateData;
TextView title;
public ItemViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.reminderTitle);
itemView.setOnClickListener(this);
}
public void bind(int id, String title, String desc, String date){
this.idData = id;
this.titleData = title;
this.descData = desc;
this.dateData = date;
this.title.setText(title);
}
#Override
public void onClick(View v) {
// You can access all the data here
Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
}
}
}