SQLite Database not showing data to custom ListView - java

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;
}
}

Related

How do I delete data from SQLITE database by ID

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 +"'");
}

Access SQLite Helper From Adapter

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

SQLiteException: unknown database

I made a custom Adapter for my ListView following this tutorial.
But when I run my app on my device, it gives an error when it's starting.
The error appears when the onCreate() method of the MainActivity tries to call the getData() method of the NotesDbHelper class.
Can you help me?
MainActivity.java
public class MainActivity extends Activity
{
private EditText mEditText;
private Button mButton;
NotesCustomAdapter notesCustomAdapter = null;
ListView listView = null;
NotesDbHelper database = null;
ArrayList<Notes> notes = null;
/** Called when the activity is first created.
* #param savedInstanceState */
#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);
database = new NotesDbHelper(this);
notes = database.getData();
notesCustomAdapter= new NotesCustomAdapter(this,R.layout.notes_details,notes);
listView = (ListView) findViewById(R.id.simpleListView);
listView.setAdapter(notesCustomAdapter);
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) {
database.insertNote(input);
}
}
});
listView.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) {
database.deleteNote(which);
notes.remove(positionToRemove);
notesCustomAdapter.remove(String.valueOf(positionToRemove));
notesCustomAdapter.notifyDataSetChanged();
}});
adb.show();
}
});
}
#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;
}
return super.onOptionsItemSelected(item);
}
}
NotesDbHelper.java
public class NotesDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Notes.db";
public static final String NOTES_TABLE_NAME = "Notes.user";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NAME = "n_text";
public NotesDbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + NOTES_TABLE_NAME +
"(_id integer primary key AUTOINCREMENT NOT NULL," + NOTES_COLUMN_NAME +
")"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_NAME);
onCreate(db);
}
public boolean insertNote(String text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("n_text", text);
db.insert(NOTES_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList<Notes> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Notes> notes = new ArrayList<Notes>();
Cursor result = db.rawQuery("select * from "+ NOTES_TABLE_NAME , null);
while(result.moveToNext()){
notes.add( new Notes(result.getString(result.getColumnIndex(NOTES_COLUMN_NAME))));
}
return notes;
}
public boolean updateNotes(int id, int text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("n_text", text);
db.update(NOTES_TABLE_NAME, contentValues, "id = ? ", new String[]{Integer.toString(id)});
return true;
}
public Integer deleteNote(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(NOTES_TABLE_NAME,
"id = ? ",
new String[]{Integer.toString(id)});
}
}
Notes.java
public class Notes {
String text;
public Notes(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
NotesCustomAdapter.java
public class NotesCustomAdapter extends ArrayAdapter{
private Context context;
private ArrayList<Notes> notes;
public NotesCustomAdapter(Context context, int textViewResourceId, ArrayList objects) {
super(context,textViewResourceId, objects);
this.context= context;
notes=objects;
}
private class ViewHolder
{
TextView text;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder=null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.notes_details, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Notes textNotes = notes.get(position);
holder.text.setText(textNotes.getText());
return convertView;
}
}
LogCat
the first line says:
java.lang.RuntimeException: Unable to start activity ComponentInfo{agenda.com/agenda.com.MainActivity}: android.database.sqlite.SQLiteException: unknown database Notes (code 1): while compiling: create table Notes.user(_id integer primary key AUTOINCREMENT NOT NULL,n_text)
Why Notes.user? You're putting an unnecessary dot. Go compare to the link you've referenced.
Just use Notes or UserNotes

Android Custom ArrayAdapter from SQLite results

I want to make a custom adapter out of my SQLite results, however, I'm stuck doing so :( How would I make a custom adapter out of this code?
I'm getting my Database records through my DbHelper.java
Here's my ListAdapter Class
public class ListAdapter extends ArrayAdapter<Note> {
Context mContext;
int layoutResourceId;
Note notes[] = null;
public ListAdapter(Context context, int layoutResourceId, Note[] notes) {
super(context, layoutResourceId, notes);
this.mContext = context;
this.layoutResourceId = layoutResourceId;
this.notes = notes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
NoteHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NoteHolder();
holder.noteSubject = (TextView)row.findViewById(R.id.editTextSubject);
holder.noteDesc = (TextView)row.findViewById(R.id.editTextTODO);
row.setTag(holder);
}
else
{
holder = (NoteHolder)row.getTag();
}
Note note = notes[position];
holder.noteSubject.setText(note.noteSubject);
holder.noteDesc.setText(note.noteDescription);
return row;
}
static class NoteHolder
{
TextView noteSubject;
TextView noteDesc;
}
}
Here's my Note.java Class
public class Note {
int id;
String noteSubject;
String noteDescription;
public Note(){}
public Note(String note_subject, String note_desc){
super();
this.noteSubject = note_subject;
this.noteDescription= note_desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNoteSubject() {
return noteSubject;
}
public void setNoteSubject(String noteSubject) {
this.noteSubject = noteSubject;
}
public String getNoteDescription() {
return noteDescription;
}
public void setNoteDescription(String noteDescription) {
this.noteDescription = noteDescription;
}
}
MY DbHelper.java
This is what returns the data, i want to get these results into a Listview.
public List<Note> getAllNotes() {
List<Note> notes = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
int id = Integer.parseInt(cursor.getString(0));
String noteSubject = cursor.getString(1);
String noteDesc = cursor.getString(2);
Note note = new Note();
note.id = id;
note.noteSubject = noteSubject;
note.noteDescription = noteDesc;
notes.add(note);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Log.d("getAllNotes()", notes.toString());
return notes;
}
Don't quite caught your question.
You just need to pass your data items inside the adapter and fill your custom views inside the getView(). I can't really see the problem. Here you have a nice tutorial about Usage of ArrayAdapter:https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView Hope this will help.

get the data when an Item is clicked in recyclerview

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();
}
}
}

Categories