Database refusing to delete item - java

I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?

I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.

Related

How to create delete method in SQLite for deleting single item not the whole checklist?

I'll post only relevant code.
This is Activity which adds checklist to database.
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
ArrayList<String> itemList;
ArrayList<String> stateList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView() {
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.requestFocus();
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view) {
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
} else
checklistHelper.setStatus("0");
itemList.add(etChecklistItem.getText().toString());
stateList.add(checklistHelper.getStatus());
}
StringBuilder stringBuilder = new StringBuilder();
for (String items : itemList) {
stringBuilder.append(items);
stringBuilder.append("\n");
}
StringBuilder stringBuilder1 = new StringBuilder();
for (String state : stateList) {
stringBuilder1.append(state);
stringBuilder1.append("\n");
}
String items = stringBuilder.toString();
String state = stringBuilder1.toString();
dbHelper.insertChecklist(state, items, DateTime.date(), DateTime.time(), System.currentTimeMillis());
finish();
break;
}
return true;
}
}
This is insert checklist method in SQLiteHelper class.
public boolean insertChecklist(String status, String content, String date, String time, long now){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(CHECKLIST_STATUS, status);
c.put(CHECKLIST_CONTENT, content);
c.put(CHECKLIST_DATE, date);
c.put(CHECKLIST_TIME, time);
c.put(CHECKLIST_NOW, now);
long id = sqLiteDatabase.insert(CHECKLIST_TABLE, null, c);
Log.d("check", "checklist inserted -> ID = " + id);
return true;
}
This is the delete method for deleting the whole checklist, not for individual items.
public void deleteChecklist(long id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(CHECKLIST_TABLE, CHECKLIST_ID + " =? ", new String[] {String.valueOf(id)});
}
Here I want a method like above, but only for deleting selected item, like this image.. Look at this image.
look this image

pass data from one activity to another and save it

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance
You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.
I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

ListView Checked Checkboxes

I am creating an Android application for communication learning
I make a List of word, it is contains a CheckBoxes and TextView, TextView is to display the the word, the use of the CheckBox is to determine what item in the ListView that I selected.
I store the id of the word in SQLite with "submit" button. when i close and open the activity again i want to see the checked checkboxes but this code only save to my database but not show the selected item when i open the activity again
this is the Activity
public class PerkembanganLevel1 extends AppCompatActivity{
private ContentDao contentDao;
private ChildDao childDao;
private Child anakYangDipilih;
public Global global;
private AssessmentDao assessmentDao;
private Assessment assessment;
String idYangSudahBisa;
PerkembanganAdapter perkembanganAdapter = null;
ContentHistory contentHistory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perkembangan_level1);
contentDao = new ContentDao(this);
contentDao.open();
childDao = new ChildDao(this);
childDao.open();
anakYangDipilih = ((Global) getApplicationContext()).getChild();
idYangSudahBisa = anakYangDipilih.getLevel1();
ArrayList<ContentHistory> listKataLevel1 = (ArrayList<ContentHistory>) contentDao.getAllWordByLevel(1);
perkembanganAdapter = new PerkembanganAdapter(this, R.layout.list_perkembangan, listKataLevel1);
ListView level1 = findViewById(R.id.LVPlv1);
level1.setAdapter(perkembanganAdapter);
Log.i("listKataLevel1 ", String.valueOf(listKataLevel1));
level1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
contentHistory = (ContentHistory) parent.getItemAtPosition(position);
}
});
findViewById(R.id.BtnPLv1Submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
idYangSudahBisa = perkembanganAdapter.idYangSudahBisa();
anakYangDipilih.getId();
anakYangDipilih.setLevel1(idYangSudahBisa);
anakYangDipilih.setCreatedBy(((Global) getApplicationContext()).getTherapist().getId());
anakYangDipilih.setUpdatedBy(((Global) getApplicationContext()).getTherapist().getId());
anakYangDipilih.setCreatedDate(new Date());
anakYangDipilih.setUpdatedDate(new Date());
anakYangDipilih = childDao.saveChild(anakYangDipilih);
Toast.makeText(PerkembanganLevel1.this, "Perkembangan Anak pada level 1 Berhasil Diperbarui", Toast.LENGTH_SHORT).show();
}
});
}
}
this is the adapter
public class PerkembanganAdapter extends ArrayAdapter<ContentHistory> {
String idYangSudahBisa;
private ChildDao childDao;
private Child anakYangDipilih;
public ArrayList<ContentHistory> contentHistories;
public PerkembanganAdapter(Context context, int id, ArrayList<ContentHistory> contentHistories){
super(context, id, contentHistories);
this.contentHistories = new ArrayList<>();
this.contentHistories.addAll(contentHistories);
childDao = new ChildDao(getContext());
childDao.open();
anakYangDipilih = ((Global) context.getApplicationContext()).getChild();
this.idYangSudahBisa = anakYangDipilih.getLevel1();
}
private class ViewHolder{
TextView title;
CheckBox checkBoxes;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_perkembangan, null);
viewHolder = new ViewHolder();
viewHolder.title = convertView.findViewById(R.id.TVListPerkembangan);
viewHolder.checkBoxes = convertView.findViewById(R.id.CBListPerkembangan);
convertView.setTag(viewHolder);
viewHolder.checkBoxes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
ContentHistory contentHistory = (ContentHistory) checkBox.getTag();
contentHistory.setSelected(checkBox.isChecked());
if (checkBox.isChecked()){
idYangSudahBisa = idYangSudahBisa + ","+contentHistory.getId();
//Toast.makeText(getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show();
} else {
idYangSudahBisa = idYangSudahBisa.replace(","+contentHistory.getId(), "");
//Toast.makeText(getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show();
}
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ContentHistory contentHistory = contentHistories.get(position);
viewHolder.title.setText(contentHistory.getTitle());
viewHolder.checkBoxes.setChecked(contentHistory.getSelected());
viewHolder.checkBoxes.setTag(contentHistory);
return convertView;
}
public String idYangSudahBisa(){
return this.idYangSudahBisa;
}
}
...
There is no need for a submit button as you can update (toggele) the database in real time when the checkbox is clicked.
The important aspect is the addition of a method in ContentDao such as :-
public void toggleCheckedById(long id) {
db.execSQL(
"UPDATE " + TABLE_NAME +
" SET " + COLUMN_CHECKED + " = NOT " + COLUMN_CHECKED +
" WHERE " + COLUMN_ID + "=?",
new String[]{String.valueOf(id)}
);
}
This equates to UPDATE the_table SET the_check_column = NOT the_check_column WHERE the_id_column =?
noting that ? is replaced (bound) using the 2nd paarmeter passed to execSQL which in this case is a String[] containing a single element which is the id of the row to be changed.
This can be called from the CheckBox's onClick passing the id extracted from the view's Tag.
Consider this cutdown version of your code :-
The database helper (perhaps your Global.java class) DatabaseHelper.java :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "perkembangan.db";
public static final int DBVERSION = 1;
private static DatabaseHelper sInstance;
private DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
public static synchronized DatabaseHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new DatabaseHelper(context);
}
return sInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createContentSQL = "CREATE TABLE IF NOT EXISTS " + ContentDao.TABLE_NAME +
"(" +
ContentDao.COLUMN_ID + " INTEGER PRIMARY KEY, " +
ContentDao.COLUMN_NAME + " TEXT, " +
ContentDao.COLUMN_CHECKED + " INTEGER DEFAULT 0" +
")";
db.execSQL(createContentSQL);
/* ADD SOME TESTING DATA WHEN THE DATABASE IS CREATED */
ContentValues cv = new ContentValues();
for (int i=0; i < 3; i++) {
cv.clear();
cv.put(ContentDao.COLUMN_NAME,"Name" + String.valueOf(i));
db.insert(ContentDao.TABLE_NAME,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public static String qualifyColumnName(String table, String column) {
return table + "." + column;
}
}
Note that this adds 3 rows for testing.
You probably don't need this.
ContentDao.java (an interpretation thereof) :-
public class ContentDao {
private static DatabaseHelper sInstance;
private static SQLiteDatabase db;
public static final String TABLE_NAME = "content";
public static final String COLUMN_ID = BaseColumns._ID;
public static final String QUALIFIEDCOLUMN_ID = DatabaseHelper.qualifyColumnName(TABLE_NAME,COLUMN_ID);
public static final String COLUMN_NAME = "name";
public static final String COLUMN_CHECKED = "checked";
public ContentDao(Context context) {
db =(sInstance = DatabaseHelper.getInstance(context)).getWritableDatabase();
}
public void toggleCheckedById(long id) {
db.execSQL(
"UPDATE " + TABLE_NAME +
" SET " + COLUMN_CHECKED + " = NOT " + COLUMN_CHECKED +
" WHERE " + COLUMN_ID + "=?",
new String[]{String.valueOf(id)}
);
}
public SQLiteDatabase getDb() {
return db;
}
public int updateCheckedById(ContentHistory ch) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_CHECKED,ch.isChecked());
return db.update(TABLE_NAME,cv,COLUMN_ID + "=?",new String[]{String.valueOf(ch.getId())});
}
public ArrayList<ContentHistory> getContentHistory() {
ArrayList<ContentHistory> rv = new ArrayList<>();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(new ContentHistory(csr.getLong(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_NAME)),
csr.getInt(csr.getColumnIndex(COLUMN_CHECKED))> 0)
);
}
csr.close();
return rv;
}
public class ContentHistory {
private long id;
private String name;
private boolean checked;
ContentHistory(long id, String name, boolean checked) {
this.id = id;
this.name = name;
this.checked = checked;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
}
NOTE for convenience the ContentHistory class has been included
name has been used instead of Title (didn't realise until later)
As said the important addition is the toggleCheckedById method.
PerkembanganAdapter.java
public class PerkembanganAdapter extends ArrayAdapter<ContentDao.ContentHistory> {
ContentDao contentDao;
public ArrayList<ContentDao.ContentHistory> contentHistories;
public PerkembanganAdapter(Context context, int id, ArrayList<ContentDao.ContentHistory> contentHistories){
super(context, id, contentHistories);
contentDao = new ContentDao(context);
this.contentHistories = new ArrayList<>();
this.contentHistories.addAll(contentHistories);
/*
childDao = new ChildDao(getContext());
childDao.open();
anakYangDipilih = ((Global) context.getApplicationContext()).getChild();
this.idYangSudahBisa = anakYangDipilih.getLevel1();
*/
}
private class ViewHolder{
TextView title;
CheckBox checkBoxes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_perkembangan, null);
viewHolder = new ViewHolder();
viewHolder.title = convertView.findViewById(R.id.TVListPerkembangan);
viewHolder.checkBoxes = convertView.findViewById(R.id.CBListPerkembangan);
convertView.setTag(viewHolder);
viewHolder.checkBoxes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
ContentDao.ContentHistory contentHistory = (ContentDao.ContentHistory) checkBox.getTag();
contentHistory.setChecked(checkBox.isChecked());
contentDao.toggleCheckedById(contentHistory.getId()); //<<<<< will update (toggle) database in real time
/* NOT NEEDED
if (checkBox.isChecked()){
//idYangSudahBisa = idYangSudahBisa + ","+contentHistory.getId();
//Toast.makeText(v.getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show();
} else {
//idYangSudahBisa = idYangSudahBisa.replace(","+contentHistory.getId(), "");
//Toast.makeText(getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show();
}
*/
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ContentDao.ContentHistory contentHistory = contentHistories.get(position);
viewHolder.title.setText(contentHistory.getName());
viewHolder.checkBoxes.setChecked(contentHistory.isChecked());
viewHolder.checkBoxes.setTag(contentHistory);
return convertView;
}
}
Note much of the original code has been commeneted out and just the important code needed to demonstrate has been left in.
Names that appear to be foreign language names have also been omitted/changed for convenience.
Obviously the code will have to be adapted to suit. It is the technique that is being demonstrated.
PerkembanganLevel1.java the Activity :-
public class PerkembanganLevel1 extends AppCompatActivity{
private ContentDao contentDao;
private ListView level1;
private PerkembanganAdapter perkembanganAdapter;
private ArrayList<ContentDao.ContentHistory> contentHistory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perkembangan_level1);
level1 = this.findViewById(R.id.level1);
contentDao = new ContentDao(this);
manageListView();
/*contentDao.open();
childDao = new ChildDao(this);
childDao.open();
anakYangDipilih = ((Global) getApplicationContext()).getChild();
idYangSudahBisa = anakYangDipilih.getLevel1();
*/
/*
ArrayList<ContentDao.ContentHistory> listKataLevel1 = (ArrayList<ContentDao.ContentHistory>) contentDao.getAllWordByLevel(1);
perkembanganAdapter = new PerkembanganAdapter(this, R.layout.list_perkembangan, listKataLevel1);
//ListView level1 = findViewById(R.id.LVPlv1);
level1.setAdapter(perkembanganAdapter);
Log.i("listKataLevel1 ", String.valueOf(listKataLevel1));
level1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
contentHistory = (ContentDao.ContentHistory) parent.getItemAtPosition(position);
}
});
findViewById(R.id.BtnPLv1Submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
idYangSudahBisa = perkembanganAdapter.idYangSudahBisa();
anakYangDipilih.getId();
anakYangDipilih.setLevel1(idYangSudahBisa);
anakYangDipilih.setCreatedBy(((Global) getApplicationContext()).getTherapist().getId());
anakYangDipilih.setUpdatedBy(((Global) getApplicationContext()).getTherapist().getId());
anakYangDipilih.setCreatedDate(new Date());
anakYangDipilih.setUpdatedDate(new Date());
anakYangDipilih = childDao.saveChild(anakYangDipilih);
Toast.makeText(PerkembanganLevel1.this, "Perkembangan Anak pada level 1 Berhasil Diperbarui", Toast.LENGTH_SHORT).show();
}
});
*/
}
/* Will refresh the Listview when returning from an invoked activity just in case data has changed */
#Override
protected void onResume() {
super.onResume();
manageListView();
}
private void manageListView() {
contentHistory = contentDao.getContentHistory();
if (perkembanganAdapter == null) {
perkembanganAdapter = new PerkembanganAdapter(this,R.layout.list_perkembangan,contentHistory);
level1.setAdapter(perkembanganAdapter);
} else {
perkembanganAdapter.notifyDataSetChanged(); // Not really needed if updating when checked
}
}
}
Demo results
When first run :-
Second Run row 2 ticked and then restarted
Third Run all 3 checkeck boxes reversed and then restarted

App is getting crashed when I'm trying to delete Data from database and refreshing ListView

I'm learning android programming and trying to delete data from database using a button in custom ListView but, unfortunately, my App is getting crashed when I hit Yes On Alert DialogBox.
FenceActivity
public class FenceActivity extends AppCompatActivity {
List<Fence> fenceList;
SQLiteDatabase sqLiteDatabase;
ListView listViewFences;
FenceAdapter fenceAdapter;
DataBaseHelper dataBaseHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.savedfences);
listViewFences = findViewById(R.id.fencesListView);
fenceList = new ArrayList<>();
showFencesFromDatabase();
}
public void showFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
public void reloadFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
fenceList.clear();
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
}
ShowFencesFromDatabase method I'm using to get Data from the database.
FenceAdapter
public class FenceAdapter extends ArrayAdapter<Fence> {
Context context;
int listLayoutRes;
List<Fence> fenceList;
DataBaseHelper dataBaseHelper;
FenceActivity fenceActivity;
public FenceAdapter(Context context, int listLayoutRes, List<Fence> fenceList) {
super(context, listLayoutRes, fenceList);
this.context = context;
this.listLayoutRes = listLayoutRes;
this.fenceList = fenceList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_layout_fences, null);
}
final Fence fence = fenceList.get(position);
TextView textViewSno = convertView.findViewById(R.id.textViewSnoLabel);
TextView textViewLat = convertView.findViewById(R.id.textViewLatitudeValue);
TextView textViewLon = convertView.findViewById(R.id.textViewLongitudeValue);
TextView textViewRadi = convertView.findViewById(R.id.textViewRadiusValue);
textViewSno.setText(Integer.toString(fence.getSno()));
textViewLat.setText(String.valueOf(fence.getLat()));
textViewLon.setText(String.valueOf(fence.getLon()));
textViewRadi.setText(Integer.toString(fence.getRadius()));
Button buttonDel = convertView.findViewById(R.id.buttonDeleteFence);
buttonDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper = new DataBaseHelper(context);
fenceActivity = (FenceActivity)context;
dataBaseHelper.deleteDataById(fence);
fenceActivity.reloadFencesFromDatabase();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
return convertView;
}
DatabaseHelper Class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
public static final String DB_NAME = "FenceDatabase";
private static final String TABLE_NAME = "FenceData";
private static final String col1 = "Sno";
private static final String col2 = "Latitude";
private static final String col3 = "Longitude";
private static final String col4 = "Radius";
Context context;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + col1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + col2 + " REAL , " + col3 + " REAL , " + col4 + " INTEGER)";
sqLiteDatabase.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean addData(Double lat, Double lon, int radi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, lat);
contentValues.put(col3, lon);
contentValues.put(col4, radi);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
return true;
}
public Cursor getAllData() {
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
return cursor;
}
public void deleteDataById(Fence fence) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String sql = "DELETE FROM FenceData WHERE Sno = ?";
sqLiteDatabase.execSQL(sql, new Integer[]{fence.getSno()});
}
}
Fence class
public class Fence {
int radius,sno;
double lat,lon;
public Fence( int sno,double lat, double lon,int radius) {
this.radius = radius;
this.sno = sno;
this.lat = lat;
this.lon = lon;
}
public int getRadius() {
return radius;
}
public int getSno() {
return sno;
}
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
}
Errors
2019-06-30 19:06:08.658 22783-22875/com.abhishakkrmalviya.fencetest E/LB: fail to open file: No such file or directory
2019-06-30 19:06:11.473 22783-22783/com.abhishakkrmalviya.fencetest E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted
What steps should I take to make App work properly, I mean to delete data from the database?
Initialise dataBaseHelper = new DataBaseHelper(context); before invoking dataBaseHelper.deleteDataById();
The problem is within FenceAdapter.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper.deleteDataById();
fenceActivity.showFencesFromDatabase();
}
});
The problem is that dataBaseHelper is not initialized before its usege.
It can be solve by adding a line dataBaseHelper = new DataBaseHelper(context); at the end of adapter's constructor.

Error when adding new item to SQLite database from EditTexts

I have an application that supposed to take the text that the user enters from 4 EditTexts and a Spinner, and create a new item in the database when a button is clicked. (Image Below)
I have created a method in my database helper class that adds a new item, so in this activity I create a new item, and then pass that item to the method that should create it in the database. But for some reason weird text appear on the screen instead of a new item in the RecyclerView.
I don't know why I get the strings from the editTexts and the int (Which is the Arrival Time) and the string from the spinner and I pass it to a new item (Train) but this error keeps happening.
Here are my DatabaseHelper Class:
public class TrainDatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "train.db";
public static final String TABLE_NAME = "train";
public static final String COLUMN_ID ="_id";
public static final String COLUMN_PLATFORM = "platform";
public static final String COLUMN_ARRIVAL_TIME = "arrival_time";
public static final String COLUMN_STATUS = "status";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_DESTINATION_TIME = "destination_time";
public static final String[] COLUMNS = {COLUMN_ID, COLUMN_PLATFORM, COLUMN_ARRIVAL_TIME
, COLUMN_STATUS,COLUMN_DESTINATION,COLUMN_DESTINATION_TIME};
private static TrainDatabaseHelper sInstance;
public synchronized static TrainDatabaseHelper getInstance(Context context) {
if (sInstance == null){
sInstance = new TrainDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
private TrainDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_PLATFORM + " TEXT, "
+ COLUMN_ARRIVAL_TIME + " INTEGER, "
+ COLUMN_STATUS+ " TEXT, "
+ COLUMN_DESTINATION + " TEXT, "
+ COLUMN_DESTINATION_TIME + " TEXT"
+ ")"
);
addTrain(db, new Train(0, "Albion Park Platform 1", 3,"On Time",
"Allawah", "14:11"));
addTrain(db, new Train(1, "Arncliffe Platform 2", 4, "Late",
"Central", "14:34"));
addTrain(db, new Train(2, "Artarmion Platform 3", 7, "On Time",
"Ashfield", "15:01"));
addTrain(db, new Train(3, "Berowra Platform 4", 12, "Late",
"Beverly", "15:18"));
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion){
case 1:
db.execSQL("alter table " + TABLE_NAME + " add column description TEXT");
case 2:
db.execSQL("alter table " + TABLE_NAME + " add column air_conditioned TEXT");
}
}
public void addTrain(Train train){
addTrain(getWritableDatabase(), train);
}
private void addTrain(SQLiteDatabase db, Train train){
ContentValues values = new ContentValues();
values.put(COLUMN_PLATFORM, train.getPlatform());
values.put(COLUMN_ARRIVAL_TIME, train.getArrivalTime());
values.put(COLUMN_STATUS, train.getStatus());
values.put(COLUMN_DESTINATION, train.getDestination());
values.put(COLUMN_DESTINATION_TIME, train.getDestinationTime());
db.insert(TABLE_NAME,null,values);
}
public void deleteTrains (){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
public Train getTrain(int position){
return getTrains().get(position);
}
public List<Train> getTrains(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
List<Train> trains = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Train train = new Train(cursor.getInt(0),cursor.getString(1),cursor.getInt(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5));
trains.add(train);
} while (cursor.moveToNext());
}
cursor.close();
return trains;
}
Here is the activity where we add a new item (Train):
public class AddTrainActivity extends AppCompatActivity {
private Spinner mSpinner;
private EditText mPlatformEt, mArrivalEt, mDestinationEt, mDestinationTimeEt;
private String mStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_train_activity);
mPlatformEt = findViewById(R.id.platform_entry);
mArrivalEt = findViewById(R.id.arrival_time_entry);
mDestinationEt = findViewById(R.id.destination_entry);
mDestinationTimeEt = findViewById(R.id.destination_time_entry);
mSpinner = findViewById(R.id.status_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> mAdapter = ArrayAdapter.createFromResource(this,
R.array.status_array, android.R.layout.simple_spinner_item);
// Apply the adapter to the spinner
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
mSpinner.setAdapter(mAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
mStatus = getString(R.string.status_on_time);
break;
case 1:
mStatus = getString(R.string.status_late);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(AddTrainActivity.this, R.string.status_toast, Toast.LENGTH_LONG).show();
}
});
}
public void addTrainButton (View view) {
int arrivalTime = Integer.valueOf(mArrivalEt.toString());
String platform = mPlatformEt.toString();
String destination = mDestinationEt.toString();
String destinationTime = mDestinationTimeEt.toString();
Train train = new Train(4,platform,arrivalTime, mStatus,
destination ,destinationTime);
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
helper.addTrain(train);
Toast.makeText(this, R.string.add_train_toast, Toast.LENGTH_SHORT).show();
goBackHome();
}
public void cancelButton(View view) {
goBackHome();
}
public void goBackHome(){
startActivity(new Intent(AddTrainActivity.this, MainActivity.class));
}
And this is the MainActivity Class:
public class MainActivity extends AppCompatActivity {
private RecyclerView mTrainsRv;
private TrainAdapter mTrainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTrainsRv = findViewById(R.id.train_rv);
mTrainsRv.setLayoutManager(new LinearLayoutManager(this));
mTrainAdapter = new TrainAdapter(this);
mTrainsRv.setAdapter(mTrainAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
/** a FAB onClick Listener that starts a new activity to add a train */
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,AddTrainActivity.class));
}
});
}
#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 */
switch (item.getItemId()) {
case R.id.action_delete:
// TODO deleting all trains from database
mTrainAdapter.notifyDataSetChanged();
return true;
case R.id.action_refresh:
return true;
case R.id.action_quit:
Toast.makeText(this, R.string.quit_menu,
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
}
Thanks in advance and if you need more code let me know.
The problem was I forgot to do .getText() before doing .toString()
example:
mPlatformEt.getText().toString();
instead of
mPlatformEt.toString();

Categories

Resources