ListView Checked Checkboxes - java

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

Related

I am creating Android Note app using fragments, but I can't cope with the error that occurs in NoteFragment.java

NoteFragment.java
public class NoteFragment extends Fragment {
private ListView noteListView;
private Note note;
List <Note> notes = new ArrayList<Note>();
private Button add;
private NoteAdapter noteAdapter;
private String title = "title";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_note, container, false);
noteListView = (ListView) view.findViewById(R.id.noteListView);
initWidgets();
loadFromDBtoMemory();
setNoteAdapter();
return view;
}
private void initWidgets() {
noteListView = getActivity().findViewById(R.id.noteListView);
add = getActivity().findViewById(R.id.add_fragment);
}
private void loadFromDBtoMemory() {
SQLiteManager sqLiteManager = new SQLiteManager(getActivity());
sqLiteManager.populateNoteListArray("");
}
private void setNoteAdapter() {
NoteAdapter noteAdapter = new NoteAdapter(getContext().getApplicationContext(), Note.nonDeletedNotes());
noteListView.setAdapter(noteAdapter);
}
#Override
public void onResume() {
super.onResume();
setNoteAdapter();
}
NoteAdapter.java
public class NoteAdapter extends ArrayAdapter<Note> {
public NoteAdapter(Context context, List<Note> notes){
super(context, 0,notes);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Note note = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.note_cell, parent, false);
}
TextView title = convertView.findViewById(R.id.cellTitle);
TextView description = convertView.findViewById(R.id.cellDesc);
TextView realTime = convertView.findViewById(R.id.realTime);
ImageView smallImg = convertView.findViewById(R.id.smallImg);
TextView impTextView = convertView.findViewById(R.id.ImpTextView);
title.setText(note.getTitle());
description.setText(note.getDescription());
String formatedTime = DateFormat.getDateTimeInstance().format(note.getRealTime());
realTime.setText(formatedTime);
Uri uri = Uri.parse(note.getUri());
smallImg.setImageURI(null);
smallImg.setImageURI(uri);
if (Objects.equals(note.getSelection(), "very important")) {
impTextView.setText(note.getSelection());
impTextView.setBackgroundColor(Color.rgb(255, 0, 0));
}
if (Objects.equals(note.getSelection(), "important")) {
impTextView.setText(note.getSelection());
impTextView.setBackgroundColor(Color.rgb(255, 255, 153));
}
if (Objects.equals(note.getSelection(), "not very important")) {
impTextView.setText(note.getSelection());
impTextView.setBackgroundColor(Color.rgb(240, 248, 255));
}
return convertView;
}
}
AddFragment.java
public class AddFragment extends Fragment {
private EditText titleEditText, descEditText;
private Note selectedNote;
private ImageView newImg;
private FloatingActionButton addImg;
private ConstraintLayout imgContainer;
private final int PICK_IMAGE_CODE = 123;
private String tempUri = "empty";
private String[] importancy = {"very important", "important", "not very important"};
private Spinner spinner;
private String selectedItem;
private View view;
private Button saveNote;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
SQLiteManager sqLiteManager = new SQLiteManager(getActivity());
spinner = view.findViewById(R.id.importancy);
titleEditText = view.findViewById(R.id.titleEditText);
descEditText = view.findViewById(R.id.descriptionEditText);
addImg = view.findViewById(R.id.addImg);
imgContainer = view.findViewById(R.id.imgContainer);
newImg = view.findViewById(R.id.newImg);
spinner = view.findViewById(R.id.importancy);
saveNote = view.findViewById(R.id.saveNote);
saveNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveNote(view);
}
});
ArrayAdapter<String> importancyAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, importancy);
importancyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(importancyAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedItem = adapterView.getSelectedItem().toString();
for (int u = 0; u < importancy.length; u++) {
if (importancy[i] == "very important")
view.setBackgroundColor(Color.rgb(255, 0, 0));
if (importancy[i] == "important")
view.setBackgroundColor(Color.rgb(255, 255, 153));
if (importancy[i] == "not very important")
view.setBackgroundColor(Color.rgb(240, 248, 255));
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void saveNote(View view) {
SQLiteManager sqLiteManager = new SQLiteManager(getActivity());
String title = String.valueOf(titleEditText.getText());
String desc = String.valueOf(descEditText.getText());
long realTime = System.currentTimeMillis();
String uri = String.valueOf(tempUri);
String selection = String.valueOf(selectedItem);
if(selectedNote == null){
int id = Note.noteArrayList.size();
Note newNote = new Note(id, title, desc, realTime, uri, selection);
Note.noteArrayList.add(newNote);
System.out.println(Note.noteArrayList);
sqLiteManager.addNoteToDatabase(newNote);
Toast.makeText(getActivity().getApplicationContext(), "Note saved", Toast.LENGTH_SHORT).show();
}
else {
selectedNote.setTitle(title);
selectedNote.setDescription(desc);
selectedNote.setRealTime(realTime);
selectedNote.setUri(uri);
selectedNote.setSelection(selection);
sqLiteManager.updateNoteInDB(selectedNote);
}
}
}
Note.java
public class Note {
public static ArrayList<Note> noteArrayList = new ArrayList<>();
public static String NOTE_EDIT_EXTRA = "noteEdit";
private int id;
private String title;
private String description;
private long realTime;
private String uri = "empty";
private String selection;
private Date deleted;
public Note(int id, String title, String description, long realTime, String uri, String selection, Date deleted) {
this.id = id;
this.title = title;
this.description = description;
this.realTime = realTime;
this.uri = uri;
this.selection = selection;
this.deleted = deleted;
}
public Note(int id, String title, String description, long realTime, String uri, String selection) {
this.id = id;
this.title = title;
this.description = description;
this.realTime = realTime;
this.uri = uri;
this.selection = selection;
deleted = null;
}
public static Note getNoteForID(int passedNoteID) {
for(Note note : noteArrayList){
if(note.getId() == passedNoteID){
return note;
}
}
return null;
}
public static ArrayList<Note> nonDeletedNotes(){
ArrayList<Note> nonDeleted = new ArrayList<>();
for(Note note : noteArrayList){
if(note.getDeleted() == null){
nonDeleted.add(note);
}
}
return nonDeleted;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getRealTime() {return realTime; }
public void setRealTime(long realTime) {this.realTime = realTime;}
public String getUri (){return uri;}
public void setUri(String uri) {this.uri = uri;}
public String getSelection(){return selection;}
public void setSelection(String selection) {this.selection = selection;}
public Date getDeleted() {
return deleted;
}
public void setDeleted(Date deleted) {
this.deleted = deleted;
}
}
**
SQLiteManager.java**
public class SQLiteManager extends SQLiteOpenHelper {
private static SQLiteManager sqLiteManager;
private static final String DATABASE_NAME = "NoteDB";
private static final int DATABASE_VERSION = 3;
private static final String TABLE_NAME = "Note";
private static final String COUNTER = "Counter";
private static final String ID_FIELD = "id";
private static final String TITLE_FIELD = "title";
private static final String DESC_FIELD = "desc";
private static final String REAL_TIME = "realtime";
private static final String IMAGE_URI = "uri";
private static final String SELECTED_ITEM = "selection";
private static final String DELETED_FIELD = "deleted";
#SuppressLint("SimpleDateFormat")
private static final DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
public SQLiteManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static SQLiteManager instanceOfDatabase(Context context) {
if (sqLiteManager == null) {
sqLiteManager = new SQLiteManager(context);
}
return sqLiteManager;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
StringBuilder sql;
sql = new StringBuilder()
.append(" CREATE TABLE ")
.append(TABLE_NAME)
.append("(")
.append(COUNTER)
.append(" INTEGER PRIMARY KEY AUTOINCREMENT, ")
.append(ID_FIELD)
.append(" INT, ")
.append(TITLE_FIELD)
.append(" TEXT, ")
.append(DESC_FIELD)
.append(" TEXT, ")
.append(REAL_TIME)
.append(" TEXT, ")
.append(IMAGE_URI)
.append(" TEXT, ")
.append(SELECTED_ITEM)
.append(" TEXT, ")
.append(DELETED_FIELD)
.append(" TEXT)");
sqLiteDatabase.execSQL(sql.toString());
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
//if(newVersion ==2)
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
onCreate(sqLiteDatabase);
//sqLiteDatabase.execSQL("ALTER TABLE " + "Note" + " ADD COLUMN " +REAL_TIME + " TEXT");
}
public void addNoteToDatabase(Note note) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ID_FIELD, note.getId());
contentValues.put(TITLE_FIELD, note.getTitle());
contentValues.put(DESC_FIELD, note.getDescription());
contentValues.put(REAL_TIME, String.valueOf(note.getRealTime()));
contentValues.put(IMAGE_URI, note.getUri());
contentValues.put(SELECTED_ITEM, note.getSelection());
contentValues.put(DELETED_FIELD, getStringFromDate(note.getDeleted()));
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
}
public void populateNoteListArray(String title_field) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String Selection = "title" + " like ?";
Cursor result = sqLiteDatabase.query(TABLE_NAME, null, Selection, new String[]{"%" + title_field + "%"}, null, null, null);
while (result.moveToNext()) {
int id = result.getInt(1);
String title = result.getString(2);
String desc = result.getString(3);
String time = result.getString(4);
long realtime = Long.parseLong(time);
String imgUri = result.getString(5);
String selection = result.getString(6);
String stringDeleted = result.getString(7);
Date deleted = getDatefromString(stringDeleted);
Note note = new Note(id, title, desc, realtime, imgUri, selection, deleted);
Note.noteArrayList.add(note);
}
}
public void updateNoteInDB(Note note){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ID_FIELD, note.getId());
contentValues.put(TITLE_FIELD, note.getTitle());
contentValues.put(DESC_FIELD, note.getDescription());
contentValues.put(SELECTED_ITEM, note.getSelection());
contentValues.put(DELETED_FIELD, getStringFromDate(note.getDeleted()));
sqLiteDatabase.update(TABLE_NAME, contentValues, ID_FIELD + " =?", new String[]{String.valueOf(note.getId())});
}
private String getStringFromDate(Date date) {
if(date == null){
return null;
}
return dateFormat.format(date);
}
private Date getDatefromString(String string){
try
{
return dateFormat.parse(string);
}
catch (ParseException | NullPointerException e)
{
return null;
}
}
The problem:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: andrii.sosnytskyi.nure.mynote_v2, PID: 16771
java.lang.RuntimeException: Unable to start activity ComponentInfo{andrii.sosnytskyi.nure.mynote_v2/andrii.sosnytskyi.nure.mynote_v2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at andrii.sosnytskyi.nure.mynote_v2.NoteFragment.setNoteAdapter(NoteFragment.java:55)
at andrii.sosnytskyi.nure.mynote_v2.NoteFragment.onCreateView(NoteFragment.java:37)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
at android.app.Activity.performStart(Activity.java:7029)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Please, explain me how to fix it.
According to the stack trace, in this method noteListView is null:
private void setNoteAdapter() {
NoteAdapter noteAdapter = new NoteAdapter(getContext().getApplicationContext(), Note.nonDeletedNotes());
noteListView.setAdapter(noteAdapter);
}

Why my bookmarked words doesn't saved to sqlite database if i want to add them from another fragment?

The main problem is that when i add bookmark codes from direct recyclerview it works perfectly fine but when i add those codes to another fragment it just only show a toast that bookmark is added or deleted but that bookmarked word doesn't show in favorite list.
Here is my Database codes
public class DictionaryDB {
public static final String ID = "id";
public static final String SANSKRIT = "sanskrit_word";
public static final String BANGLA = "bn_word";
public static final String STATUS = "status";
public static final String USER = "user_created";
public static final String TABLE_NAME = "sanskrit_words";
public static final String BOOKMARKED = "b";
public static final String USER_CREATED = "u";
DatabaseInitializer initializer;
public DictionaryDB(DatabaseInitializer initializer) {
this.initializer = initializer;
}
public void addWord(String sanskritWord, String banglaWord) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "INSERT INTO " + TABLE_NAME + " (" + SANSKRIT +
", " + BANGLA + ", " + USER + ") VALUES ('" + sanskritWord +
"', '" + banglaWord + "', '" + USER_CREATED + "') ";
db.execSQL(sql);
}
public List<Word> getWords(String sanskritWord) {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + SANSKRIT + " LIKE ? ";
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{sanskritWord + "%"});
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
//************Waka Maka Saka *****************//******************//
public List<Word> getBookmarkedWords() {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + STATUS + " = '" + BOOKMARKED + "'";
Cursor cursor = db.rawQuery(sql, null);
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
}
cursor.close();
db.close();
return wordList;
}
public void bookmark(int id) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '"
+ BOOKMARKED + "' WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
}
public void deleteBookmark(int id) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '' " +
" WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
}
}
My RecyclerView codes
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>implements Filterable {
private Context context;
private List<Word> wordList;
List<Word> filwordList;
private DictionaryDB dictionaryDB;
public RecyclerViewAdapter(Context context, List<Word> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Word>(itemList);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
// Create and return a new holder instance
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Word word = wordList.get(position);
holder.msanskrit.setText(word.sanskrit);
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
}
else {
holder.bookmark.setImageResource(R.drawable.cards_heart_grey);
}
holder.bookmark.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, holder.bookmark);
}
});
}
private void bookMarkWord(final Word word, final ImageButton bookmark) {
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
dictionaryDB.deleteBookmark(word.id);
word.status = "";
bookmark.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(context, "Bookmark Deleted", Toast.LENGTH_SHORT).show();
}
else {
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
bookmark.setImageResource(R.drawable.cards_heart);
Toast.makeText(context, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
}
/*
public void updateEntries(List<Word> wordList) {
if (wordList == null) {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Sorry!")
.setMessage("Your phone doesn't support pre-built database")
.create();
dialog.show();
} else {
this.wordList = wordList;
notifyDataSetChanged();
}
}
*/
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Word> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Word item : filwordList) {
if (item.getSanskrit().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Word>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView msanskrit;
final ImageButton bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
msanskrit = itemView.findViewById(R.id.tvSansTerm);
// mbangla = itemView.findViewById(R.id.tvBnTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
#Override
public void onClick(View view) {
int position = this.getAdapterPosition();
Word word = wordList.get(position);
String sanskrit = word.getSanskrit();
String bangla = word.getBangla();
// String sources = term.getMSources();
Intent intent = new Intent(context, TermThreeDetailsActivity.class);
intent.putExtra("Rsanskrit", sanskrit);
intent.putExtra("Rbangla", bangla);
// intent.putExtra("Rsources", sources);
context.startActivity(intent);
}
}
}
My Detalis Fragment codes
public class TermThreeDetailsFragment extends Fragment {
private Toolbar toolbar;
TextView termTextView,descTextView;
private ImageButton imgBtn;
private DictionaryDB dictionaryDB;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
termTextView = view.findViewById(R.id.textvWord);
descTextView = view.findViewById(R.id.textvDesc);
imgBtn = view.findViewById(R.id.favAddBtn);
getData();
toolbar = ((Toolbar) view.findViewById(R.id.toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
WordCheck();
return view;
}
public void getData() {
Intent intent = getActivity().getIntent();
String sanskrit = intent.getStringExtra("Rsanskrit");
String bangla = intent.getStringExtra("Rbangla");
termTextView.setText(sanskrit);
descTextView.setText(bangla);
}
private void WordCheck() {
final Word word = new Word();
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
imgBtn.setImageResource(R.drawable.cards_heart);
}
else {
imgBtn.setImageResource(R.drawable.cards_heart_grey);
}
imgBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, imgBtn);
}
});
}
private void bookMarkWord(final Word word, final ImageButton imgBtn) {
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
dictionaryDB.deleteBookmark(word.id);
word.status = "";
imgBtn.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(getContext(), "Bookmark Deleted", Toast.LENGTH_SHORT).show();
}
else {
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
imgBtn.setImageResource(R.drawable.cards_heart);
Toast.makeText(getContext(), "Bookmark Added", Toast.LENGTH_SHORT).show();
}
}}
My Favorite Fragment codes
public class FavoritesFragment extends Fragment {
RecyclerView rv;
private LinearLayoutManager layoutManager;
DictionaryDB dictionaryDB;
FavoriteAdapter rvFavAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.favorites_fragment,container,false);
Toolbar toolbar = ((Toolbar) view.findViewById(R.id.fav_toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
List<Word> wordList = dictionaryDB.getBookmarkedWords();
rv = ((RecyclerView) view.findViewById(R.id.rvFavorites));
if (wordList.size() != 0) {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
rvFavAdapter = new FavoriteAdapter(getContext(), dictionaryDB,wordList);
rv.setAdapter(rvFavAdapter);
} else {
Toast.makeText(getContext(), "You have no bookmark yet.", Toast.LENGTH_SHORT).show();
}
return view;
}
}
When i use bookmark codes from direct RecyclerView
When i use same bookmark codes from another fragment this happens
Any help will be heavily appreciated 🙏
Problem Solved
Just add those to RecyclerView
int position = this.getAdapterPosition();
Word word = wordList.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
And add this codes to Fragment Class
word = new Word(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
termTextView.setText(word.getSanskrit());
descTextView.setText(word.getBangla());
}
*** You need to make you POJO class Parcelable to pass objects between fragments. ***

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.

Database refusing to delete item

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.

Android Listview not updating after delete item

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();

Categories

Resources