Android - deleting items from ListView but not from Database - java

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

Related

Android studio displaying data from sqlite local db

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.

How Can I delete item on my SQliteOpenhelper [duplicate]

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.

Delete selected item from listview and sqlite Android

I am having trouble with my programming project. I am creating a shopping application and all I need is deleting the selected data from listview and mysqlite database with a click of a button. I also created a query on my sqlite where it will delete primary key autoincrement integer.
Here is my class:
public class CartPage extends AppCompatActivity {
DatabaseHelper myDB;
public Button button_delete;
public Button button_home;
public TextView textView_totalAmount;
public TextView textView_PK;
public ListView listView_datas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page);
myDB = new DatabaseHelper(this);
listView_datas = (ListView) findViewById(R.id.listView_ShoppingData);
button_delete = (Button) findViewById(R.id.button_deleteData);
button_home = (Button) findViewById(R.id.button_HomePage);
textView_totalAmount = (TextView) findViewById(R.id.textView_DisplayTotalAmount);
int total = myDB.addPrice();
textView_totalAmount.setText("$" + Integer.toString(total));
final ArrayList<String> list_cart = new ArrayList<>();
final Cursor data = myDB.getPrice_cart();
if (data.getCount() == 0) {
Toast.makeText(CartPage.this, "The Database is empty..", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
list_cart.add(data.getString(1) + "\n" +
data.getString(2) + "\n");
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, list_cart);
listView_datas.setAdapter(listAdapter);
}
}
button_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goHome = new Intent(CartPage.this, FirstPage.class);
startActivity(goHome);
}
});
}
}
Here is my database helper query for deleting the data by primary key
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(table_Cart,"number = ?" , new String[] {number} );
}
For this scenario I was thinking on using but I am not sure how to do it.
listView_datas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
I also saw where when you hold the selected item it would get deleted. I don't mind that as long as it deletes the data.
Thank you!
I would suggest you implement a long click listener in your ListView and on long click on the item in your list, it will show an option to delete the corresponding item in your list. Here's a sample code that can help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View view, final int position, long arg3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RecipeList.this);
alertDialog.setTitle("Delete");
alertDialog.setMessage(yourList.get(position));
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteSelectedItem(yourList.get(position))
}
});
alertDialog.show();
return true;
}
});
And yes, you need to call notifyDataSetChanged() in your deleteSelectedItem() function to see the effect of the delete in your list.
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(table_Cart,"number = ?" , new String[] {number} );
// Update your list here
// Remove the deleted item from the list that you have passed to the adapter. Then call notifyDataSetChanged
updateYourListCart();
myAdapter.notifyDataSetChanged();
}

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

Realm data not saving java

I am trying to save data into a RealmListafter calling a dialog box. The dialog is supposed to take the name of the new object, a FixtureInfo, add it to the RealmList, and then move to the next activity. However after moving to the next activity and pressing the back button the ListView populated with that RealmList doesn't show the object just created. There is no error it just doesn't show up. Any ideas?
EDIT added in RealmBaseAdapter as beeeneder suggest I do and problem persists.
first activity
public class RoomDescription extends ActionBarActivity {
public AlertDialog.Builder dialogBuilder;
public RealmList<FixtureInfo> myFixtures = new RealmList<>();
public String RoomName;
public String FixtureName;
public RealmList<Rooms> myRooms = new RealmList<>();
private Realm realm;
public Rooms rooms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_description);
//get room name
TextView textFixture = (TextView) findViewById(R.id.RoomName);
Bundle extras = getIntent().getExtras();
if (extras != null) {
RoomName = extras.getString("txtString");
textFixture.setText(RoomName);
}
//initiate realm instant to get CompanyInfo object, Room object, and populate myRoom and myFixtures
realm = Realm.getInstance(this);
rooms = realm.where(Rooms.class).equalTo("Name", RoomName).findFirst();
realm.beginTransaction();
CompanyInfo companyinfo = realm.where(CompanyInfo.class).findFirst();
myRooms = companyinfo.getRooms();
myFixtures = rooms.getFixtureInfos();
realm.commitTransaction();
populateListView();
}
#Override
protected void onResume() {
super.onResume();
LoadInfo();
}
#Override
protected void onPause() {
super.onPause();
SaveInfo();
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
private void setFixtureName()
{
//dialog to add fixture to room and set its name
dialogBuilder = new AlertDialog.Builder(this);
final EditText txtInput = new EditText(this);
dialogBuilder.setTitle("New Fixture");
dialogBuilder.setMessage("What is the fixture name?");
dialogBuilder.setView(txtInput);
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//initiate realm instant
Realm realm = Realm.getInstance(getApplicationContext());
realm.beginTransaction();
//get fixture name and create FixtureInfo object
FixtureName = txtInput.getText().toString();
FixtureInfo fixtureInfo = realm.createObject(FixtureInfo.class);
fixtureInfo.setName(FixtureName);
fixtureInfo.setRoomName(RoomName);
myFixtures.add(fixtureInfo);
realm.commitTransaction();
//save changes
SaveInfo();
//start new activity
Intent i = new Intent(RoomDescription.this, FixtureDescription.class);
i.putExtra("textString", FixtureName);
i.putExtra("txtString", RoomName);
populateListView();
Toast.makeText(getApplicationContext(), "Fixture has been added.", Toast.LENGTH_SHORT).show();
startActivity(i);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SaveInfo();
}
});
AlertDialog dialogFixtureName = dialogBuilder.create();
dialogFixtureName.show();
}
private void setRoomName()
{
//same as setRoomName in RoomList.java
dialogBuilder = new AlertDialog.Builder(this);
final EditText txtInput = new EditText(this);
dialogBuilder.setTitle("New Room");
dialogBuilder.setMessage("What is the room name?");
dialogBuilder.setView(txtInput);
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Realm realm = Realm.getInstance(getApplicationContext());
realm.beginTransaction();
String txtString = txtInput.getText().toString();
Rooms rooms = realm.createObject(Rooms.class);
rooms.setName(txtString);
myRooms.add(rooms);
realm.commitTransaction();
SaveInfo();
realm.close();
Intent i = new Intent(RoomDescription.this, RoomDescription.class);
i.putExtra("txtString", txtString);
Toast.makeText(getApplicationContext(), "Room has been added.", Toast.LENGTH_SHORT).show();
populateListView();
startActivity(i);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SaveInfo();
}
});
AlertDialog dialogFixtureName = dialogBuilder.create();
dialogFixtureName.show();
}
private void removeFixture()
{
//remove fixture from room
dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Select Fixture to Remove");
dialogBuilder.setSingleChoiceItems(myFixtures.toArray(new String[myFixtures.size()]), -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//initiate realm instant
Realm realm = Realm.getInstance(getApplicationContext());
//remove fixture info from room
realm.beginTransaction();
myFixtures = rooms.getFixtureInfos();
myFixtures.remove(which);
//save change
SaveInfo();
populateListView();
Toast.makeText(getApplicationContext(), "Fixture has been removed.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialogFixtureName = dialogBuilder.create();
dialogFixtureName.show();
}
private void populateListView()
{
//on click for the list of FixtureInfo connected to the room
ListView list = (ListView) findViewById(R.id.FixtureList);
RealmResults<FixtureInfo> results = realm.where(FixtureInfo.class).equalTo("RoomName", RoomName).findAll();
FixtureListAdapter adapter = new FixtureListAdapter(this, results, true);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
default:
Intent i = new Intent(RoomDescription.this, FixtureDescription.class);
TextView textItem = (TextView) view;
String FixtureName = textItem.getText().toString();
i.putExtra("textString", FixtureName);
i.putExtra("txtString", RoomName);
startActivity(i);
break;
}
}
});
}
public void SaveInfo()
{
//save info or update info
realm.beginTransaction();
rooms.setName(RoomName);
rooms.setFixtureInfos(myFixtures);
realm.copyToRealmOrUpdate(rooms);
realm.commitTransaction();
}
public void LoadInfo()
{
//load info from specific room
realm.beginTransaction();
myFixtures = rooms.getFixtureInfos();
realm.commitTransaction();
}
#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_room_description, 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();
switch (item.getItemId())
{
case R.id.newFixture:
setFixtureName();
break;
case R.id.removeFixture:
removeFixture();
break;
case R.id.add:
setRoomName();
break;
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
case R.id.summary:
startActivity(new Intent(getApplicationContext(), Summary.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
RealmBaseAdapter class
public class FixtureListAdapter extends RealmBaseAdapter<FixtureInfo> implements ListAdapter {
private static class ViewHolder{
TextView FixtureName;
}
public FixtureListAdapter(Context context, RealmResults<FixtureInfo> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.simple_list_item_1,
parent, false);
viewHolder = new ViewHolder();
viewHolder.FixtureName = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
FixtureInfo fixtureInfo = realmResults.get(position);
viewHolder.FixtureName.setText(fixtureInfo.getName());
return convertView;
}
}
FixtureInfo class
public class FixtureInfo extends RealmObject{
#PrimaryKey
private String RoomName;
#Ignore
private String Name;
private String Description;
private String Wattage;
private String Run_Time;
private String Bulbs_Out;
private String Notes;
private int Count;
public String getRoomName() {
return RoomName;
}
public void setRoomName(String roomName) {
RoomName = roomName;
}
public void setCount(int count) {
Count = count;
}
public int getCount() {
return Count;
}
public void setName(String name) {
Name = name;
}
public void setDescription(String description) {
Description = description;
}
public void setWattage(String wattage) {
Wattage = wattage;
}
public void setRun_Time(String run_Time) {
Run_Time = run_Time;
}
public void setBulbs_Out(String bulbs_Out) {
Bulbs_Out = bulbs_Out;
}
public void setNotes(String notes) {
Notes = notes;
}
public String getName() {
return Name;
}
public String getDescription() {
return Description;
}
public String getWattage() {
return Wattage;
}
public String getRun_Time() {
return Run_Time;
}
public String getBulbs_Out() {
return Bulbs_Out;
}
public String getNotes() {
return Notes;
}
}
I suggest you set a break pointer in onClick to check fixtureInfo you tried to add there. since the RoomName is the primary key, so if you are trying to change a FixtrueInfo with a different RoomName there, i don't expect you will see any changes in the ListView since the RealmResults is based on the original name.
And couple of other problems:
transaction is only needed for writing, no need for reading.
If the object is created by Realm.createObject, no need to call copyToRealmOrUpdate anymore
I suggest you to spend a couple of more minutes on our examples http://github.com/realm/realm-java/tree/master/examples . And also, the mechanism behind the realm-java is that we using Proxy object to overload getters/setters. It is not difficult. You can find FixtureInfoRealmProxy.java in your build directory. It would be interesting and helpful to understand the whole thing, maybe you can have a quick look at that as well :)

Categories