I have a Fragment
that displays a Listview
which is populated with entries from a Database
using SQLiteOpenHelper
. I currently have ContextMenu
that allows entries to be deleted or edited. The DELETE
option functions and removes the entry from my Database
, however the EDIT
option only takes the fields entered in the Dialog
and adds a new entry to the ListView
. I want to be able to attribute the values as provided by the dialog to the entry already existing in the Database
. Thanks in advance for any input or advice.
Fragment:
public static class FragmentS extends Fragment {
private ListView saveListView;
private List<LiftSave> LiftSaves = new ArrayList<LiftSave>();
private static final int EDIT = 0, DELETE = 1;
LiftSave longClickedItemLiftSave;
DatabaseHandler dbHandler;
ArrayAdapter<LiftSave> saveAdapter;
public FragmentS() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_s,
container, false);
saveListView = (ListView) rootView.findViewById(R.id.saveListView);
registerForContextMenu(saveListView);
DatabaseHandler dbHandler;
dbHandler = new DatabaseHandler (getActivity().getApplicationContext());
if (dbHandler.getLiftSavesCount() != 0)
LiftSaves.addAll(dbHandler.getAllLiftSaves());
populateList();
saveListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemLiftSave = (LiftSave) parent.getItemAtPosition(position);
return false;
}
});
return rootView;
}
private void populateList() {
saveAdapter = new SaveListAdapter();
saveListView.setAdapter(saveAdapter);
}
public class SaveListAdapter extends ArrayAdapter<LiftSave> {
public SaveListAdapter() {
super(getActivity(), R.layout.listview_item, LiftSaves);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_item, parent, false);
LiftSave currentLiftSave = LiftSaves.get(position);
TextView liftName = (TextView) view.findViewById(R.id.liftName);
liftName.setText(currentLiftSave.getLiftName());
TextView maxValue = (TextView) view.findViewById(R.id.maxValue);
maxValue.setText(currentLiftSave.getMaxValue());
TextView liftNotes = (TextView) view.findViewById(R.id.liftNotes);
liftNotes.setText(currentLiftSave.getLiftNotes());
TextView weightAndReps = (TextView) view.findViewById(R.id.weightAndReps);
weightAndReps.setText(currentLiftSave.getRepsAndWeight());
TextView date = (TextView) view.findViewById(R.id.todayDate);
date.setText(currentLiftSave.getTodayDate());
return view;
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Save Options");
menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Save");
menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Save");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
final View dialogViewEdit = LayoutInflater.from(this.getActivity()).inflate(R.layout.edit_save, null, false);
final AlertDialog builderE = new AlertDialog.Builder(this.getActivity()).create();
TextView liftName = (TextView) getActivity().findViewById(R.id.liftName);
TextView maxValue = (TextView) getActivity().findViewById(R.id.maxValue);
TextView weightAndReps = (TextView) getActivity().findViewById(R.id.weightAndReps);
TextView liftNotes = (TextView) getActivity().findViewById(R.id.liftNotes);
TextView date = (TextView) getActivity().findViewById(R.id.todayDate);
final EditText editName = (EditText) dialogViewEdit.findViewById(R.id.liftNameED);
editName.setText(liftName.getText().toString());
EditText editNotes = (EditText) dialogViewEdit.findViewById(R.id.liftNotesED);
editNotes.setText(liftNotes.getText().toString());
EditText editWR = (EditText) dialogViewEdit.findViewById(R.id.txtWRED);
editWR.setText(weightAndReps.getText().toString());
EditText editMax = (EditText) dialogViewEdit.findViewById(R.id.txtMaxED);
editMax.setText(maxValue.getText().toString());
EditText editDate = (EditText) dialogViewEdit.findViewById(R.id.txtDateED);
editDate.setText(date.getText().toString());
Button cancel =(Button) dialogViewEdit.findViewById(R.id.btnCancel);
Button save =(Button) dialogViewEdit.findViewById(R.id.btnSave);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
builderE.dismiss();
}
});
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText editName = (EditText) dialogViewEdit.findViewById(R.id.liftNameED);
EditText editNotes = (EditText) dialogViewEdit.findViewById(R.id.liftNotesED);
EditText editWR = (EditText) dialogViewEdit.findViewById(R.id.txtWRED);
EditText editMax = (EditText) dialogViewEdit.findViewById(R.id.txtMaxED);
EditText editDate = (EditText) dialogViewEdit.findViewById(R.id.txtDateED);
//Problem
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
LiftSave liftSave = new LiftSave(dbHandler.getLiftSavesCount(), String.valueOf(editName.getText()), String.valueOf(editMax.getText()), String.valueOf(editNotes.getText()), String.valueOf(editWR.getText()), String.valueOf(editDate.getText()));
LiftSaves.add(liftSave);
dbHandler.getLiftSave(longClickedItemLiftSave.getId());
dbHandler.updateLiftSave(longClickedItemLiftSave);
saveAdapter.notifyDataSetChanged();
//Problem
}
});
builderE.setView(dialogViewEdit);
builderE.show();
break;
case DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setMessage("Are you sure you want to delete this save?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
dbHandler.deleteLiftSave(longClickedItemLiftSave);
saveAdapter.remove(longClickedItemLiftSave);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialogD = builder.create();
dialogD.show();
break;
}
return super.
onContextItemSelected(item);
}
}
Database:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "saveManager",
TABLE_SAVES = "saves",
KEY_ID = "id",
KEY_LIFTNAME = "liftName",
KEY_MAXVALUE = "txtMax",
KEY_LIFTNOTES = "txtNotes",
KEY_REPSANDWEIGHT = "repsAndWeight",
KEY_TODAYDATE = "todayDate";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_SAVES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_LIFTNAME + " TEXT," + KEY_MAXVALUE + " TEXT," + KEY_LIFTNOTES + " TEXT," + KEY_REPSANDWEIGHT + " TEXT," + KEY_TODAYDATE + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SAVES);
onCreate(db);
}
public void createLiftSave(LiftSave liftSave) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LIFTNAME, liftSave.getLiftName());
values.put(KEY_MAXVALUE, liftSave.getMaxValue());
values.put(KEY_LIFTNOTES, liftSave.getLiftNotes());
values.put(KEY_REPSANDWEIGHT, liftSave.getRepsAndWeight());
values.put(KEY_TODAYDATE, liftSave.getTodayDate());
db.insert(TABLE_SAVES, null, values);
db.close();
}
public LiftSave getLiftSave(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_SAVES, new String[] { KEY_ID, KEY_LIFTNAME, KEY_MAXVALUE, KEY_LIFTNOTES, KEY_REPSANDWEIGHT, KEY_TODAYDATE }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
LiftSave liftSave = new LiftSave(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5) );
db.close();
cursor.close();
return liftSave;
}
public void deleteLiftSave(LiftSave liftSave) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_SAVES, KEY_ID + "=?", new String[] { String.valueOf(liftSave.getId()) });
db.close();
}
public int getLiftSavesCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_SAVES, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateLiftSave(LiftSave liftSave) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LIFTNAME, liftSave.getLiftName());
values.put(KEY_MAXVALUE, liftSave.getMaxValue());
values.put(KEY_LIFTNOTES, liftSave.getLiftNotes());
values.put(KEY_REPSANDWEIGHT, liftSave.getRepsAndWeight());
values.put(KEY_TODAYDATE, liftSave.getTodayDate());
int rowsAffected = db.update(TABLE_SAVES, values, KEY_ID + "=?", new String[] { String.valueOf(liftSave.getId()) });
db.close();
return rowsAffected;
}
public List<LiftSave> getAllLiftSaves() {
List<LiftSave> liftSaves = new ArrayList<LiftSave>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_SAVES, null);
if (cursor.moveToFirst()) {
do {
liftSaves.add(new LiftSave(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return liftSaves;
}
}
LiftSave:
public class LiftSave {
private String _liftName, _maxValue, _liftNotes, _repsAndWeight, _todayDate;
private int _id;
public LiftSave(int id, String liftName, String maxValue, String liftNotes, String repsAndWeight, String todayDate) {
_id = id;
_liftName = liftName;
_maxValue = maxValue;
_liftNotes = liftNotes;
_repsAndWeight = repsAndWeight;
_todayDate = todayDate;
}
public int getId() { return _id; }
public String getLiftName() {return _liftName;}
public String getMaxValue() {return _maxValue;}
public String getLiftNotes() {return _liftNotes;}
public String getRepsAndWeight() {return _repsAndWeight;}
public String getTodayDate() {return _todayDate;}
}
Edit: One way to solve it after I just saw your LiftSave
class.
With this fix, you wouldn't have to modify the DatabaseHandler
class at all:
//Problem
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
//pass in the existing ID instead of dbHandler.getLiftSavesCount()
LiftSave liftSave = new LiftSave(longClickedItemLiftSave.getId() , String.valueOf(editName.getText()), String.valueOf(editMax.getText()), String.valueOf(editNotes.getText()), String.valueOf(editWR.getText()), String.valueOf(editDate.getText()));
//LiftSaves.add(liftSave); //Don't add to the list here
//dbHandler.getLiftSave(longClickedItemLiftSave.getId()); //looks like this is not needed
//pass in the LiftSave object with existing ID and new values
dbHandler.updateLiftSave(liftSave);
LiftSaves.clear(); //Remove all entries from the list
LiftSaves.addAll(dbHandler.getAllLiftSaves()); //Re-add all records to List including modified entry
saveAdapter.notifyDataSetChanged();
//Problem
Note that longClickedItemLiftSave.getId()
is passed in as the id
for the new LiftSave
, so when you pass it into updateLiftSave()
it updates the original entry.
Initial proposed solution, another way to solve it:
First, make your updateLiftSave()
method take an id
as a parameter, and update the record with that id
:
public int updateLiftSave(LiftSave liftSave, int id) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LIFTNAME, liftSave.getLiftName());
values.put(KEY_MAXVALUE, liftSave.getMaxValue());
values.put(KEY_LIFTNOTES, liftSave.getLiftNotes());
values.put(KEY_REPSANDWEIGHT, liftSave.getRepsAndWeight());
values.put(KEY_TODAYDATE, liftSave.getTodayDate());
//int rowsAffected = db.update(TABLE_SAVES, values, KEY_ID + "=?", new String[] { String.valueOf(liftSave.getId()) });
int rowsAffected = db.update(TABLE_SAVES, values, KEY_ID + "=?", new String[] { String.valueOf(id) });
db.close();
return rowsAffected;
}
Then, when updating, use the original id
and the new values:
//Problem
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
LiftSave liftSave = new LiftSave(dbHandler.getLiftSavesCount(), String.valueOf(editName.getText()), String.valueOf(editMax.getText()), String.valueOf(editNotes.getText()), String.valueOf(editWR.getText()), String.valueOf(editDate.getText()));
//LiftSaves.add(liftSave); //don't add it do the list
//dbHandler.getLiftSave(longClickedItemLiftSave.getId()); //looks like this is not needed
dbHandler.updateLiftSave(liftSave, longClickedItemLiftSave.getId()); //pass in the new values and the existing ID
LiftSaves.clear(); //Remove all entries from the list
LiftSaves.addAll(dbHandler.getAllLiftSaves()); //Re-add all records to List including modified entry
saveAdapter.notifyDataSetChanged();
//Problem
Update: You might also need to add a call to clear the list in onCreateView()
in order to ensure that you never get duplicate entries in the List, and that the List always mirrors the entries currently in the database:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//........
if (dbHandler.getLiftSavesCount() != 0){
LiftSaves.clear(); //Clear the list just in case
LiftSaves.addAll(dbHandler.getAllLiftSaves());
}
Update 2: As for your last issue, try using the LiftSaves
List instead of the parent
AdapterView:
saveListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//longClickedItemLiftSave = (LiftSave) parent.getItemAtPosition(position);
longClickedItemLiftSave = LiftSaves.get(position);
return false;
}
});