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();
}
}
}
Related
This question already has answers here:
How to delete items from sqlite database with SQLiteOpenHelper class
(2 answers)
Closed 2 years ago.
I save my recyclerview with SQliteopenhelper . I can add item with edittext varibles . I use Itemtouchhelper for swip to delete item . How can ı delete item on SQliteopenhelper . Can you be fast
todoactivity.java
public class todoactivity extends AppCompatActivity {
TextView title;
Button back;
ImageButton gorevo;
RecyclerView recyclerView;
List<String>Listsx = new ArrayList<>();
TodoActivityAdpter adapterx;
DatabaseHelper4 myDBxxx;
TextView textView;
CheckBox checkBox;
long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todoactivity);
recyclerView=findViewById(R.id.recyclerviewxx);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapterx=new TodoActivityAdpter(Listsx);
recyclerView.setAdapter(adapterx);
title=findViewById(R.id.titlex);
textView=findViewById(R.id.text_viewx);
gorevo = findViewById(R.id.gorevo);
myDBxxx = new DatabaseHelper4(this);
Cursor datax = myDBxxx.getListContents();
if(datax.getCount() == 0){
}else{
while(datax.moveToNext()){
Listsx.add(datax.getString(1));
ListAdapter listAdapterx = new ArrayAdapter<>(this,R.layout.todoactivity_item,R.id.textitem,Listsx);
adapterx.notifyItemInserted(Listsx.size()-1);
}
}
gorevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(todoactivity.this);
bottomSheetDialog.setContentView(R.layout.bottomsheetlayout3);
bottomSheetDialog.show();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
EditText editText = bottomSheetDialog.findViewById(R.id.editx);
Button ekle = bottomSheetDialog.findViewById(R.id.ekle);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editText.getText().toString();
Listsx.add(text);
AddDataxxx(text);
adapterx.notifyItemInserted(Listsx.size()-1);
bottomSheetDialog.hide();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
});
}
});
back=findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(todoactivity.this, pomodoroscreen.class);
startActivity(i);
overridePendingTransition(0,0);
}
});
ItemTouchHelper.SimpleCallback simpleCallback = 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) {
int positionx = viewHolder.getAdapterPosition();
Listsx.remove(positionx);
adapterx.notifyItemRemoved(positionx);
int id = recyclerView.getChildAt(positionx).getId();
myDBxxx.deleteItem(id);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void AddDataxxx(String newEntry) {
boolean insertDatax = myDBxxx.addDataxxx(newEntry);
}
}
DatabaseHelper.java
public class DatabaseHelper4 extends SQLiteOpenHelper {
public static final String DATABASE_NAME4 = "mylistxxx.db";
public static final String TABLE_NAME4 = "mylist_dataxxx";
public static final String COL14 = "iDxxx";
public static final String COL24 = "ITEM1xxx";
public DatabaseHelper4(Context context) {
super(context, DATABASE_NAME4, null, 1);
}
#Override
public void onCreate(SQLiteDatabase dbxxx) {
String createTable = "CREATE TABLE " + TABLE_NAME4 + " (iDxxx INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1xxx TEXT)";
dbxxx.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase dbxxx, int oldVersion, int newVersion) {
dbxxx.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME4);
onCreate(dbxxx);
}
public boolean addDataxxx(String textt) {
SQLiteDatabase dbxxx = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL24, textt);
long result = dbxxx.insert(TABLE_NAME4, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase dbxxx = this.getWritableDatabase();
Cursor dataxxx = dbxxx.rawQuery("SELECT * FROM " + TABLE_NAME4, null);
return dataxxx;
}
public void deleteItem(int iDxxx) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME4 + " WHERE " + COL14 + " = " +
iDxxx);
}
}
Adapter.java
public class TodoActivityAdpter extends RecyclerView.Adapter<TodoActivityAdpter.Holder> {
List<String>Listsx;
public TodoActivityAdpter(List<String>itemxxx){
this.Listsx = itemxxx;
}
#NonNull
#Override
public TodoActivityAdpter.Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todoactivity_item,parent,false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TodoActivityAdpter.Holder holder, int position) {
holder.textView.setText(Listsx.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
holder.textView.setTextColor(view.getResources().getColor(R.color.grey));
} else {
holder.textView.setTextColor(view.getResources().getColor(R.color.Color_black));
}
}
});
}
#Override
public int getItemCount() {
return Listsx.size();
}
public class Holder extends RecyclerView.ViewHolder {
CheckBox checkBox;
TextView textView;
List<String>Listsx;
RecyclerView recyclerView;
Context mContext;
public Holder(View view) {
super(view);
textView=view.findViewById(R.id.text_viewx);
checkBox=view.findViewById(R.id.checkbox);
recyclerView=view.findViewById(R.id.recyclerviewxx);
}
}
}
Thats my java classes . My activity is todoactivity . My SQliteopenhelper is DatabaseHelper.java . My Adapter is adapter.java . I can delete item on my recyclerview but ı cant delete item on my database
You can easily delete item from your table by just below code.
//Add method in your database class.
public void deleteItem(int iDxxx) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME4 + " WHERE " + COL14 + " =
" + iDxxx);
}
and Just Call this method from where you are deleting item.
I'm attempting to get the data that is saved in my the SQLite database into a custom ListView in my app. It seems the adaptor is working okay because it inflating the layout, however, there is no data in the views. I'm hoping it is a simple fix and I appreciate any input on this :)
Activity where data will be shown:
public class SavedGameScreen extends AppCompatActivity {
ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_game_screen);
lv1 = findViewById(R.id.lv1);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadData();
}
private void loadData() {
arrayList = databaseHelper.getAllData();
myAdaptor = new MyAdaptor(this, arrayList);
lv1.setAdapter(myAdaptor);
myAdaptor.notifyDataSetChanged();
}
}
Database Helper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "savedGames.db";
public static final String TABLE_NAME = "savedGamesTable";
public static final String COL_1 = "ID";
public static final String COL_2 = "lName";
public static final String COL_3 = "lScore";
public static final String COL_4 = "rName";
public static final String COL_5 = "rScore";
public static final String COL_6 = "notes";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table "+TABLE_NAME+" (ID INTEGER PRIMARY KEY AUTOINCREMENT, lName TEXT," +
"lScore INTEGER, rName TEXT, rScore INTEGER, notes TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String lName, int lScore, String rName, int rScore, String notes) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, lName);
contentValues.put(COL_3, lScore);
contentValues.put(COL_4, rName);
contentValues.put(COL_5, rScore);
contentValues.put(COL_6, notes);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public ArrayList<GameStats> getAllData() {
ArrayList<GameStats> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String lName = cursor.getString(1);
int lScore = cursor.getInt(2);
String rName = cursor.getString(3);
int rScore = cursor.getInt(4);
String notes = cursor.getString(5);
GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
arrayList.add(gameStats);
}
return arrayList;
}
}
myAdaptor:
public class MyAdaptor extends BaseAdapter {
Context context;
ArrayList<GameStats> arrayList;
public MyAdaptor(Context context, ArrayList<GameStats> arrayList){
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_saved_games, null);
TextView lName = convertView.findViewById(R.id.lName);
TextView lScore = convertView.findViewById(R.id.lScore);
TextView rName = convertView.findViewById(R.id.rName);
TextView rScore = convertView.findViewById(R.id.rScore);
TextView notes = convertView.findViewById(R.id.notes);
GameStats gameStats = arrayList.get(position);
lName.setText(gameStats.getlName());
lScore.setText(String.valueOf(gameStats.getlScore()));
rName.setText(gameStats.getrName());
rScore.setText(String.valueOf(gameStats.getrScore()));
notes.setText(gameStats.getNotes());
return convertView;
}
}
Below is what I am getting when I try to view the data
Model class:
public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getlScore() {
return lScore;
}
public void setlScore(int lScore) {
this.lScore = lScore;
}
public int getrScore() {
return rScore;
}
public void setrScore(int rScore) {
this.rScore = rScore;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
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 +"'");
}
Code
public class ChatData extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "MessagePlus";
public ChatData(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAllQuestions3(MessagesAdapter usageSettings2) {
return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
}
Adapter
final ChatData mHelper = new ChatData(this);
final Cursor csr = mHelper.getAllQuestions3(this);
Nothing is working for context in adapter. This shows message to change the Helper classes context to the Adapters name and if i do that theres a red line under context in the helper... If i directly try to access like ChatData.getWritableDatabase it shows that u cant access a non static method from a static class and if i make that method in helper static it shows error there saying class cant be static... one error is leading to another and i dont know what to do so can someone help me out please
EDIT
Full Adapter Code
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MessageViewHolder>{
private List<SQLiteHelper> mMessagesHelperList;
private FirebaseAuth mAuth;
ChatData mHelper = new ChatData(this);
Cursor csr = mHelper.getAllQuestions3();
public MessagesAdapter(List<SQLiteHelper> mMessagesHelperList) {
this.mMessagesHelperList = mMessagesHelperList;
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView messageText;
public MessageViewHolder(View view) {
super(view);
messageText = (TextView)view.findViewById(R.id.message_text_layout);
}
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_chat,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#Override
public void onBindViewHolder(final MessageViewHolder holder, int position) {
String mSender = null;
String mMessage = null;
String mTime;
String mSeen = null;
String mTimer;
String mType;
while (csr.moveToNext()) {
mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
mTime = csr.getString(csr.getColumnIndex(KEY_TIME));
mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
}
SQLiteHelper messagesHelper = mMessagesHelperList.get(position);
#Override
public int getItemCount() {
return mMessagesHelperList.size();
}
}
Activity
final MainData mHelper = new MainData(this); //Change the name to your Helper Class name
final Cursor csr = myDBHlpr.getAllQuestions3(this);
messageList.setAdapter(mAdapter);
while (csr.moveToNext()) {
String mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
String mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
String mTime = csr.getString(csr.getColumnIndex(KEY_TIME));
String mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
String mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
String mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
messages.add(new SQLiteHelper(mSender, mMessage, mTime, mSeen, mTimer, mType));
}
The following will likely cause some of your issues. That is you are saying that the method should be passed a MesagesAdapter, when as it stands there is no reason to pass anything into the getAllQuestions3 method.
public Cursor getAllQuestions3(MessagesAdapter usageSettings2) {
return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
Trying changing the above to
public Cursor getAllQuestions3() {
return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
and use
ChatData mHelper = new ChatData(this);
Cursor csr = mHelper.getAllQuestions3();
instead of
final ChatData mHelper = new ChatData(this,ChatData.DATABASE_NAME,null,ChatData.DATABASE_VERSION);
final Cursor csr = mHelper.getAllQuestions3(this);
Noting that the above lines should be in the Activity's onCreate method or a method invoked from onCreate so that you have a valid context (i.e. this).
Edit 1
Note that the above has been changed as according to ChatData you need to provided 4 parameters for the instantiation of a ChatData object.
I'd suggest changing the constructor to :-
public ChatData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and then you could use ChatData mHelper = new ChatData(this);.
Working Example
The following is a working example based upon the code you have given.
The database helper ChatData.java
public class ChatData extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "MessagePlus";
public static final String TABLE_CHAT_DATA = "chatdata";
public static final String COL_CHATDATA_ID = BaseColumns._ID;
public static final String COL_CHATDATA_TIMESTAMP = "timestamp";
public static final String COL_CHATDATA_MESSAGE = "message";
public static final String COL_CHATDATA_USER = "user";
public ChatData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_CHAT_DATA + "(" +
COL_CHATDATA_ID + " INTEGER PRIMARY KEY, " +
COL_CHATDATA_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP," +
COL_CHATDATA_MESSAGE + " TEXT, " +
COL_CHATDATA_USER + " INTEGER" +
")";
db.execSQL(crt_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAllQuestions3() {
return this.getWritableDatabase().query(TABLE_CHAT_DATA,null,null,null,null,null,null);
}
public long addMessage(String message, long user) {
ContentValues cv = new ContentValues();
cv.put(COL_CHATDATA_MESSAGE,message);
cv.put(COL_CHATDATA_USER,user);
SQLiteDatabase db = this.getWritableDatabase();
return db.insert(TABLE_CHAT_DATA,null,cv);
}
}
Note modified to crate a table and to allow rows to be added to the table.
Note the constructor.
The Custom Adapter (Cursor Adapter) MessageAdapter.java
public class MessageAdapter extends CursorAdapter {
public MessageAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View rv = LayoutInflater.from(context).inflate(
R.layout.messagelist_item,
parent,
false
);
return rv;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView mUser = view.findViewById(R.id.user);
TextView mTimestamp = view.findViewById(R.id.timestamp);
TextView mMessage = view.findViewById(R.id.message);
mUser.setText(cursor.getString(cursor.getColumnIndex(ChatData.COL_CHATDATA_USER)));
mTimestamp.setText(cursor.getString(cursor.getColumnIndex(ChatData.COL_CHATDATA_TIMESTAMP)));
mMessage.setText(cursor.getString(cursor.getColumnIndex(ChatData.COL_CHATDATA_MESSAGE)));
}
}
The layout used in the list messagelist_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/user"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/timestamp"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/message"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content" />
</LinearLayout>
The code in the Activity to list the messages via the adapter (MainActivty.java)
public class MainActivity extends AppCompatActivity {
ChatData mDBHlpr;
Cursor mCsr;
MessageAdapter mMesaageAdapter;
ListView mMessageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessageList = this.findViewById(R.id.messagelist);
mDBHlpr = new ChatData(this);
addSomeData();
mCsr = mDBHlpr.getAllQuestions3();
mMesaageAdapter = new MessageAdapter(this,mCsr,false);
mMessageList.setAdapter(mMesaageAdapter);
}
private void addSomeData() {
mDBHlpr.addMessage("Hello",1);
mDBHlpr.addMessage("Hi",2);
mDBHlpr.addMessage("How are you?",1);
mDBHlpr.addMessage("I'm OK thanks, and you?",2);
mDBHlpr.addMessage("Good.",1);
}
}
Result
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.