I cant seem to find any solutions to this problem on the internet. basically im working on an app that lets the user create workouts and view them and I'm struggling with the view part.
My database is all set up with user input using the fields exercise, sets and reps, the user creates a workout and the contents of the table used to build it are copied to a new one and the table is cleared to take in new input.
I want to create a recycler view using the table names, pass the selected item name to the next fragment and use the users selection to determine what data will be shown in the next recycler view.
Is this possible and if so please show me how, I'm supposed to have this app ready in a couple of days for an assignment
any help would be appreciated, thanks - Ian
To clairfy, you would like to make list of the list?
Use one to many relationship or map using room.
I have done such implementation days ago feel free to ask.
https://developer.android.com/training/data-storage/room/relationships?fbclid=IwAR3P_rK8OeOpBpP9jgbL8FqxEKPXPvOaFwFiCMy4pIpblg_aF_9QloavHpM
https://developer.android.com/training/data-storage/room/relationships?fbclid=IwAR22XINRNxTs3b_KOleeYwjGuIwjUA90S3tvpMWkf1dKYjvDDo5qWAbLfoE
To get previous ID or name just use simple Bundle of position(or ID) of specific element from first recyclerview and use it in the second to display the right data.
Is this possible and if so please show me how.
It is possible.
Here's a working demo that shows how.
First the class that extends SQLiteOPenHelper, as is typically used, namely DatabaseHelper in this example:-
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "thedatabase.db";
public static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
private DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
private static volatile DatabaseHelper instance = null;
public static DatabaseHelper getInstance(Context context) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(MyTable.CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int old_version, int new_version) {
}
public long insertMyTableRow(Long id, String item_name) {
ContentValues cv = new ContentValues();
cv.put(MyTable.COL_ITEM_NAME,item_name);
if (id != null && id == 0) {
cv.put(MyTable.COl_ID,id);
}
return db.insertWithOnConflict(MyTable.TABLE_NAME,null,cv,SQLiteDatabase.CONFLICT_IGNORE);
}
#SuppressLint("Range")
public MyTable[] getAllMyTableRowAsArrayOfMyTable() {
MyTable[] rv = new MyTable[0];
Cursor csr = db.query(MyTable.TABLE_NAME,null,null,null,null,null,null);
if (csr.getCount() > 0) {
rv = new MyTable[csr.getCount()];
}
int idx = 0;
while (csr.moveToNext()) {
rv[idx++] = new MyTable(
csr.getLong(csr.getColumnIndex(MyTable.COl_ID)),
csr.getString(csr.getColumnIndex(MyTable.COL_ITEM_NAME)
)
);
}
csr.close();
return rv;
}
#SuppressLint("Range")
public MyTable getAMyTableById(long id) {
MyTable rv = new MyTable(-1,"NOT FOUND");
Cursor csr = db.query(MyTable.TABLE_NAME,null,MyTable.COl_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new MyTable(csr.getLong(csr.getColumnIndex(MyTable.COl_ID)),csr.getString(csr.getColumnIndex(MyTable.COL_ITEM_NAME)));
}
csr.close();
return rv;
}
}
class MyTable {
public static final String TABLE_NAME = (MyTable.class.getSimpleName()).toLowerCase();
public static final String COl_ID = TABLE_NAME + BaseColumns._ID;
public static final String COL_ITEM_NAME = TABLE_NAME + "_item_name";
// and so on
public static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"("
+ COl_ID + " INTEGER PRIMARY KEY"
+ "," + COL_ITEM_NAME + " TEXT UNIQUE "
// and so on
+ ")";
long id;
String itemName;
MyTable(long id, String item_name) {
this.id = id;
this.itemName = item_name;
}
}
The activity that will be called MainActivity2 being passed a unique identifier of the clicked item via an Intent Extra :-
public class MainActivity2 extends AppCompatActivity {
public static final String INTENT_EXTRA_MYTABLE_ID = "ie_mytable_id";
DatabaseHelper dbHelper;
TextView itemName;
Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
itemName = this.findViewById(R.id.item_name);
done = this.findViewById(R.id.done);
dbHelper = DatabaseHelper.getInstance(this);
itemName.setText((dbHelper.getAMyTableById(this.getIntent().getLongExtra(INTENT_EXTRA_MYTABLE_ID,-99))).itemName);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
An Adapter TheAdapter etc for the RecyclerView, including Item Click and Item Long Click listeners. Clicking an item Toasts details. Long clicking starts the second activity which displays the clicked item:-
public class TheAdapter extends RecyclerView.Adapter<TheAdapter.ViewHolder> {
private MyTable[] localData;
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView textView1;
private final TextView textView2;
public ViewHolder(View view) {
super(view);
textView1 = (TextView) view.findViewById(android.R.id.text1);
textView2 = (TextView) view.findViewById(android.R.id.text2);
}
public TextView getTextView1() {
return textView1;
}
public TextView getTextView2() {
return textView2;
}
}
public TheAdapter(MyTable[] thedata) {
localData = thedata;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.getTextView1().setText(String.valueOf(localData[position].id));
holder.getTextView2().setText(localData[position].itemName);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(
view.getContext(),
"You clicked the Item named "
+ localData[holder.getAdapterPosition()].itemName
+ " the ID is " + String.valueOf(localData[holder.getAdapterPosition()].id),
Toast.LENGTH_SHORT
).show();
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(view.getContext(),MainActivity2.class);
intent.putExtra(MainActivity2.INTENT_EXTRA_MYTABLE_ID,localData[holder.getAdapterPosition()].id);
view.getContext().startActivity(intent);
return true;
}
});
}
#Override
public int getItemCount() {
return localData.length;
}
}
Finally the first/initial activity MainActivity :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbHelper;
RecyclerView myTableList;
TheAdapter adapter;
MyTable[] theDataToBeDisplayed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTableList = this.findViewById(R.id.mytable_list);
dbHelper = DatabaseHelper.getInstance(this);
addSomeTestingData();
setupOrRefreshMyTableList();
}
private void setupOrRefreshMyTableList() {
theDataToBeDisplayed = dbHelper.getAllMyTableRowAsArrayOfMyTable();
if (adapter == null) {
adapter = new TheAdapter(theDataToBeDisplayed);
myTableList.setAdapter(adapter);
myTableList.setLayoutManager(
new LinearLayoutManager(this)
);
} else {
/* handle changed data here */
}
}
private void addSomeTestingData() {
for (int i=0; i < 100; i++) {
dbHelper.insertMyTableRow(null, "A" + String.valueOf(i));
}
}
}
When run:-
When an Item (e.g. A10 (whos' id is 11)) is Long clicked :-
Clicking DONE returns to the first activity.
Related
I have created a dynamically ListView with multiple columns and a button column, as you can see in the next picture. When I click a button from a row I can Toast specific information from that row.
What I want for the next step is to somehow when I click on button "ENTER MONEY SPENT" from row 1 to create a function that can take information from "Spent/Day" [row 1 / column 3] and manipulate the information from "Remaining Money" [row 2 / column 2] and [row 2 / column 3]
My code contains MainActivity:
public class MainActivity extends AppCompatActivity {
private double budget_money;
ListView listView;
EditText enter_days;
EditText enter_budget;
ImageView btn_days;
ImageView btn_budget;
ArrayList<TableColumns> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=findViewById(R.id.listview); // from XMLmain -> ListView - listview
enter_days=findViewById(R.id.input_days); // from XMLmain -> EditText - input_days
enter_budget=findViewById(R.id.input_budget); // from XMLmain -> EditText - input_budget
btn_days=findViewById(R.id.add_days); // from XMLmain -> ImageView(as button) - add_days
btn_budget=findViewById(R.id.add_budget); // from XMLmain -> ImageView(as button) - add_budget
btn_budget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int money=Integer.parseInt(enter_budget.getText().toString());
if(enter_budget.getText()==null || money==0){
makeToast("Enter budget.");
}else{
budget_money=money; //store in global - to be used in populatelist fnc
makeToast(budget_money+ " RON added" );
}
}
});
btn_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int days=Integer.parseInt(enter_days.getText().toString());
if(enter_days.getText()==null || days==0){
makeToast("Enter days.");
}else{
populatelist(days); //calling fnc with nr of days as input
enter_days.setText("");
makeToast("Added: " + days + " Days" );
}
}
});
}
private void populatelist(int days) { //function to populate ListView with TableAdaptor class
//how can I use the following code to clear listview since "tableAdaptor" is created locally?
//tableAdaptor.clear();
//listView.setAdapter(null);
double remaining = budget_money/days;
for (int i = 1; i <=days; i++) {
arrayList.add(new TableColumns("Day " +i, "" + (remaining+i) + " RON", "Spent"));
TableAdaptor tableAdaptor = new TableAdaptor(this, R.layout.layout_list_row, arrayList); // I'm using my class TableAdaptor
listView.setAdapter(tableAdaptor);
tableAdaptor.clear();
listView.setAdapter(null);
}
}
Toast message_toast;
private void makeToast(String s){
if(message_toast!=null) message_toast.cancel();
message_toast= Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT);
message_toast.show();
}
}
Table Adaptor class:
public class TableAdaptor extends ArrayAdapter<TableColumns> {
private Context mContext;
private int mResource;
public TableAdaptor(#NonNull Context context, int resource, #NonNull ArrayList<TableColumns> objects) {
super(context, resource, objects);
this.mContext=context;
this.mResource=resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView=layoutInflater.inflate(mResource,parent,false);
TextView txtProjectName =convertView.findViewById(R.id.txt_list1);
TextView txtGroupName =convertView.findViewById(R.id.txt_list2);
EditText txtRemainingDays =convertView.findViewById(R.id.edit_list3);
Button btnMoneySpent = (Button) convertView.findViewById(R.id.btn_list);
txtProjectName.setText(getItem(position).getDays());
txtGroupName.setText(getItem(position).getRemainingMoney());
txtRemainingDays.setText(getItem(position).getSpent());
btnMoneySpent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RelativeLayout rl = (RelativeLayout)view.getParent();
TextView tv = (TextView)rl.findViewById(R.id.txt_list2);
String text = tv.getText().toString();
Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
TableColumns class:
public class TableColumns {
String Days;
String RemainingMoney;
String Spent;
public TableColumns(String days, String remainingMoney, String spent) {
Days = days;
RemainingMoney = remainingMoney;
Spent = spent;
}
public TableColumns() {
}
public String getDays() {
return Days;
}
public void setDays(String days) {
Days = days;
}
public String getRemainingMoney() {
return RemainingMoney;
}
public void setRemainingMoney(String remainingMoney) {
RemainingMoney = remainingMoney;
}
public String getSpent() {
return Spent;
}
public void setSpent(String spent) {
Spent = spent;
}
}
I am learning this on the go and while I am doing my research I found out that RecyclerView is preferred over ListView.
Should I rewrite my code with RecyclerView.Do you have some intuitive guide/example for me?
I want to clear ListView while pressing another button ( or at the begging of my populetelist function ) and I do not how since I am creating locally tableAdaptor.
How can I manipulate information from different rows from my list view while pressing the buttons from generated column 3?
I want to save my information when closing app. Is it possible?
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 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
So I have a small problem, my code deletes ListView row from ListView but every time I kill the app and then reopen it the "deleted" rows populate the ListView again.
Here's the code for delete method in DatabaseHelper class:
public void obrisiTrening(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DBKonstante.TABLE_NAME, DBKonstante.KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
And here's what my code for deleting ListView row and record from database:
rec_WorkoutItemsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_delete);
final TextView tvDialogDelete = (TextView) dialog.findViewById(R.id.tvDialogDelete);
tvDialogDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final DBPodatci infoData = dbPodatci.get(i);
dba = new DBHandler(MainActivity.this);
int position = dbPodatci.indexOf(infoData);
dbPodatci.remove(position);
DBPodatci podatki = new DBPodatci();
final int idToDelete = podatki.getItemId();
dba.obrisiTrening(idToDelete);
dba = new DBHandler(MainActivity.this);
dba.obrisiTrening(i);
rec_WorkoutItemsList.setAdapter(vjezbaAdapter);
vjezbaAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
DB PODATCI
public class DBPodatci {
public String odabraneVjezbe, recordDate;
public int itemId;
public String getOdabraneVjezbe() {
return odabraneVjezbe;
}
public void setOdabraneVjezbe(String odabraneVjezbe) {
this.odabraneVjezbe = odabraneVjezbe;
}
public String getRecordDate() {
return recordDate;
}
public void setRecordDate(String recordDate) {
this.recordDate = recordDate;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
}
Not sure what this is trying to do.
dba.obrisiTrening(idToDelete);
dba = new DBHandler(MainActivity.this);
dba.obrisiTrening(i);
You only need this
final TextView tvDialogDelete = (TextView) dialog.findViewById(R.id.tvDialogDelete);
final DBHandler dba = new DBHandler(MainActivity.this);
tvDialogDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final DBPodatci infoData = dbPodatci.get(i);
final int idToDelete = infoData.getItemId();
dbPodatci.remove(i);
dba.obrisiTrening(idToDelete);
vjezbaAdapter.notifyDataSetChanged();
dialog.dismiss();
And note: you shouldnt be using an Arraylist & ArrayAdapter here... You are using a database, so CursorAdapter is what you want
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();
}
}
}