Data are not deleted from database - android

First of all I have to tell I am still learning Android studio and maybe I missed some important and obvious staff.
Now I am facing with problem with my database, or maybe RecycleViwe i am not sure.
I my app, I am trying insert data into db and only in case if data is empty. I did it and I think that works.
Now I am trying to implement new method to read data and delete. For now I can show data in my recycleView.
My problem come with delete method. When I start app, and when delete some items it is show like everything is fine. But when I start app again, data appears again like nothing was happened.
I am not sure what cause this problem. Hope some of you guys can help me?
Below you will find parts of code. If you want to see more, feel free to ask me.
In this part of code, I call my data and showing them in recycleView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pondeljak = (Button) findViewById(R.id.buttonPonedeljak);
utorak = (Button) findViewById(R.id.buttonUtorak);
sreda = (Button) findViewById(R.id.buttonSreda);
cetvrtak = (Button) findViewById(R.id.buttonCetvrtak);
petak = (Button) findViewById(R.id.buttonPetak);
View view = getLayoutInflater().inflate(R.layout.casovi,null);
alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(view);
db = new DataDays(this);
alertDialog = alertDialogBuilder.create();
recyclerView = (RecyclerView) view.findViewById(R.id.recycleCasoviID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
casoviList = new ArrayList<>();
casoviItems = new ArrayList<>();
casoviList = db.getCasoviPonedeljak();
for (Casovi c: casoviList){
Casovi casovi = new Casovi();
casovi.setRedniBrCasa(c.getRedniBrCasa());
casovi.setNzaivCasa(c.getNzaivCasa());
casoviItems.add(casovi);
}
recycleViewAdapter = new RecycleViewAdapter(this, casoviItems);
recyclerView.setAdapter(recycleViewAdapter);
recycleViewAdapter.notifyDataSetChanged();
pondeljak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (db.casoviCountPondeljak() == 0){
Intent intent = new Intent(MainActivity.this, Unos_casova.class);
intent.putExtra("Dan", "Pondeljak");
startActivity(intent);
}else {
alertDialog.show();
}
}
});
Here is my recycleView and there is also my deletemethod. For sure core fore delete method could be written in a more simple way but I copied some of my last trials.
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
private Context context;
private List<Casovi> casoviItems;
public RecycleViewAdapter(Context context, List<Casovi> casoviItems) {
this.context = context;
this.casoviItems = casoviItems;
}
#Override
public RecycleViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prikaz_casova, parent,false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder( RecycleViewAdapter.ViewHolder holder, int position) {
Casovi casovi = casoviItems.get(position);
holder.redniBrCasPrikaz.setText(casovi.getRedniBrCasa());
holder.nazivCasPrikaz.setText(casovi.getNzaivCasa());
}
#Override
public int getItemCount() {
return casoviItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView redniBrCasPrikaz;
public TextView nazivCasPrikaz;
public Button delteBtn;
public Button editBtn;
public CardView cardView;
public int id;
public ViewHolder(View view, Context ctx) {
super(view);
context = ctx;
redniBrCasPrikaz = (TextView) view.findViewById(R.id.rednibrojCasaID);
nazivCasPrikaz = (TextView) view.findViewById(R.id.nazivcasaID);
delteBtn = (Button) view.findViewById(R.id.obrisiCasBtnID);
editBtn = (Button) view.findViewById(R.id.izmeniCasBtnID);
cardView = (CardView) view.findViewById(R.id.carViewID);
delteBtn.setOnClickListener(this);
editBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.obrisiCasBtnID:
int position = getAdapterPosition();
Casovi casovi = casoviItems.get(position);
deleteItem(casovi.getId());
notifyItemRemoved(getAdapterPosition());
break;
}
}
public void deleteItem (final int id){
DataDays db = new DataDays(context);
db.deleteCas(id);
casoviItems.remove(getAdapterPosition());
}
}
}
And here are some parts of Data Base. As I told you I am not sure what can be a problem, maybe some of these method are written in a wrong way.
public void addCasovePonedeljak (Casovi casovi){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.DAN, "Ponedeljak");
values.put(Constants.REDNI_CAS, casovi.getRedniBrCasa());
values.put(Constants.CAS, casovi.getNzaivCasa());
db.insert(Constants.TABLE_NAME, null, values);
}
public List<Casovi> getCasoviPonedeljak(){
SQLiteDatabase db = this.getReadableDatabase();
List<Casovi> casoviList = new ArrayList<>();
String pondeljakQuery = "SELECT * FROM " + Constants.TABLE_NAME + " WHERE " + Constants.DAN + " = " + " 'Ponedeljak' ";
Cursor cursor = db.rawQuery(pondeljakQuery, null);
if (cursor.moveToFirst()){
do {
Casovi casovi = new Casovi();
//casovi.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.ID))));
//casovi.setDan(cursor.getString(cursor.getColumnIndex(Constants.DAN)));
casovi.setNzaivCasa(cursor.getString(cursor.getColumnIndex(Constants.CAS)));
casovi.setRedniBrCasa(cursor.getString(cursor.getColumnIndex(Constants.REDNI_CAS)));
casoviList.add(casovi);
}while (cursor.moveToNext());
}
return casoviList;
}
public void deleteCas(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TABLE_NAME, Constants.CAS + " = ?",
new String[] {});
db.close();
}
public int casoviCountPondeljak() {
String countQuery = "SELECT * FROM " + Constants.TABLE_NAME;
//String countQuery = "SELECT COUNT(*) FROM " + Constants.TABLE_NAME + " WHERE " + Constants.DAN + " = '" + "Ponedeljak' ";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery,null);
//cursor.moveToFirst();
return cursor.getCount();
}
}

Your delete method is wrong.. You are passing parameter id but not using the id in your method as
public void deleteCas(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TABLE_NAME, Constants.CAS + " = ?",
new String[] {});
db.close();
}
It should be
public void deleteCas(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TABLE_NAME, Constants.CAS + " = ?",
new String[] {id.toString()});
db.close();
}
Syntax not tested

Related

Properly delete an sqlite entry from a recyclerView click

my app stores name and result in SQLite database and displays that in RecycleViewer. Previously I use a listView where on LongClick I could delete an item like here LuckyNumbersApk/commit/4cec554359662d557626935046b8de68fb1b5c60
now I have switched to recyclerView I can't handle it properly. When I delete it, it disapears but when I reload the fragment the deleted entry reappears again. I assume it because the item is deleted only from the list in the adapter but how can I delete it from the list that is in the fragment that actually calls the recylerViewer?
This is my Adapter:
public class DatabaseAdapter extends RecyclerView.Adapter {
List dataModelArrayList;
Context context;
public DatabaseAdapter(List<DataModel> dataModelArrayList, Context context) {
this.dataModelArrayList = dataModelArrayList;
this.context = context;
}
class Myholder extends RecyclerView.ViewHolder implements CardView.OnLongClickListener {
TextView name, result;
public Myholder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.card_name);
result = (TextView) itemView.findViewById(R.id.card_result);
CardView cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_warning_black_24dp)
.setTitle("Delete result")
.setMessage("Are you sure you want delete this result?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* This is where deletions should be handled */
int id = getAdapterPosition();
DataBHelper database = new DataBHelper(context);
database.deleteEntry(id);
dataModelArrayList.remove(id);
notifyItemRemoved(id);
notifyDataSetChanged();
database.close();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
}
#Override
public int getItemCount() {
return dataModelArrayList.size();
}}
This is DataBHelper:
public class DataBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "results_database";
public static final String RESULTS_TABLE_NAME = "results_table";
public static final String RESULTS_COLUMN_ID = "_id";
public static final String RESULTS_COLUMN_NAME = "name";
public static final String RESULTS_COLUMN_RESULT = "result";
public DataBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " (" +
RESULTS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RESULTS_COLUMN_NAME + " TEXT, " +
RESULTS_COLUMN_RESULT + " TEXT" + ")");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RESULTS_TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void saveToDB(String fname, String lname, String result) {
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
String name = fname + " " + lname;
values.put(DataBHelper.RESULTS_COLUMN_NAME, name);
values.put(DataBHelper.RESULTS_COLUMN_RESULT, result);
database.insert(DataBHelper.RESULTS_TABLE_NAME, null, values);
database.close();
}
public List<DataModel> readDB(){
List<DataModel> data=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+RESULTS_TABLE_NAME+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel= new DataModel();
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String result = cursor.getString(cursor.getColumnIndexOrThrow("result"));
dataModel.setName(name);
dataModel.setResult(result);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
public void clearDatabase() {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String clearDBQuery = "DELETE FROM "+RESULTS_TABLE_NAME;
sqLiteDatabase.execSQL(clearDBQuery);
}
public void deleteEntry(long row) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.delete(RESULTS_TABLE_NAME, RESULTS_COLUMN_ID + "=" + row, null);
}}
And this is the fragment which loads recyclerViewer
public class ResultsFragment extends Fragment {
DataBHelper database;
RecyclerView recyclerView;
DatabaseAdapter recycler;
public List<DataModel> datamodel;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_results,
container, false);
datamodel =new ArrayList<DataModel>();
recyclerView = (RecyclerView) view.findViewById(R.id.app_recycle_view);
database = new DataBHelper(getActivity());
datamodel = database.readDB();
recycler = new DatabaseAdapter(datamodel, getActivity());
RecyclerView.LayoutManager reLayoutManager =new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(reLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recycler);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
if (datamodel.isEmpty()) {
recyclerView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
}
return view;
}}
In onCreateViwHolder:
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
holder.id = dataModel.getId();
}
Add long id; into the ViewHolder, so your onClick you can delete the int id = getAdapterPosition(); and the id will be the id from the model.
To remove still use the adapter position:
dataModelArrayList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());

Data not being inserted in Table on Button Press

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}
Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~
this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed
The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()
Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

Remove item from database in recyclerview

I would like to add a feature that would allow me to remove a row from my recyclerview/database.
This feature is integrate to each item of my recyclerview as show in the following picture :
MySQLite.java:
public class MySQLite extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "character";
private static final int DATABASE_VERSION = 1;
private static final String CHARACTER_TABLE = "Ichar";
private static final String CHAR_TABLE = "create table " + CHARACTER_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT, nom TEXT, prenom TEXT , numero TEXT)";
Context context;
public MySQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CHAR_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void InsererBDD(String nom, String prenom, String numero) {
Log.d("insert", "before insert");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues entree = new ContentValues();
entree.put("nom", nom);
entree.put("prenom", prenom);
entree.put("numero", numero);
db.insert(CHARACTER_TABLE, null, entree);
db.close();
Toast.makeText(context, "insérer entrée", Toast.LENGTH_LONG);
Log.i("insert", "after insert");
db.close();
}
public List<Character> donneesBDD() {
List<Character> modelList = new ArrayList<Character>();
String query = "select * FROM " + CHARACTER_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Character model = new Character();
model.setCharacter_Id(cursor.getInt(0));
model.setNom(cursor.getString(1));
model.setPrenom(cursor.getString(2));
model.setNumero(cursor.getString(3));
modelList.add(model);
} while (cursor.moveToNext());
}
Log.d("donnee character", modelList.toString());
return modelList;
}
public void supprimerLigne(int character_Id){
SQLiteDatabase db = getWritableDatabase();
db.delete(CHARACTER_TABLE , "id" + " = ?", new String[] { String.valueOf(character_Id)});
db.close();
}
public Character getCharacterById(int Id) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " +
"nom" + "," +
"prenom" + "," +
"numero" +
" FROM " + CHARACTER_TABLE
+ " WHERE " +
"id" + "=?";
Character character = new Character();
Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(Id)});
if (cursor.moveToFirst()) {
do {
character.character_Id = cursor.getInt(cursor.getColumnIndex("id"));
character.nom = cursor.getString(cursor.getColumnIndex("nom"));
character.prenom = cursor.getString(cursor.getColumnIndex("prenom"));
character.numero = cursor.getString(cursor.getColumnIndex("numero"));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return character;
}
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
static List<Character> characters;
static Context context;
MyAdapter(Context context,List<Character> characters)
{
this.characters = new ArrayList<Character>();
this.context = context;
this.characters = characters;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int itemType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_cell, null);
MyViewHolder myViewHolder = new MyViewHolder(itemLayoutView);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
holder.nom.setText(characters.get(position).getNom());
holder.prenom.setText(characters.get(position).getPrenom());
}
#Override
public int getItemCount() {
return characters.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener,View.OnClickListener, MenuItem.OnMenuItemClickListener {
public TextView nom;
public TextView prenom;
public ImageButton delete;
public MyViewHolder(final View itemLayoutView) {
super(itemLayoutView);
nom = ((TextView) itemLayoutView.findViewById(R.id.nom));
prenom = ((TextView) itemLayoutView.findViewById(R.id.prenom));
delete = (ImageButton) itemView.findViewById(R.id.delete);
itemLayoutView.setOnClickListener(this);
itemLayoutView.setOnCreateContextMenuListener(this);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(getAdapterPosition());
}
});
}
#Override
public void onClick(View view) {
Intent intent = new Intent(context, personne.class);
Bundle extras = new Bundle();
extras.putInt("position", getAdapterPosition());
intent.putExtras(extras);
context.startActivity(intent);
Toast.makeText(MyAdapter.context, "Vous avez sélectionné un item" + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("");
menu.add(0, v.getId(), 0, "Modifier Contact");
menu.add(0, v.getId(), 0, "Supprimer Contact");
}
#Override
public boolean onMenuItemClick(MenuItem item)
{
return true;
}
}
}
can you guide me?
Thanks a lot.
You need to remove the item from your array and then notifyDataSetChanged()
fragmentOrActivity.yourArray.remove(holder.getAdapterPosition());
fragmentOrActivity.yourAdapter.notifyDataSetChanged();
Hope that helps :-)
You should write your code in onBindViewHolder method like below.
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(characters.get(position).getId());
}
});

Showing a single field from SQLite Database in an EditText

first time posting here, long time lurker. I am developing an Android app using an SQLite Database to persist data. The first view I have is a ListView where the user can add, change or delete Animal names. They can also hit an Edit Button, which brings them to a second view. This view has more details about the same animal, such as DOB and Comments, with the name and id transferred over from the first view.
The problem I am running into is I cannot figure out how to get the current animal's DOB and Comments to display in their respective EditTexts from the database. I have a save button at the bottom of this view that should save whatever info they put into these fields already, but then going back into this view needs to display whatever they have entered. My code for the two views and my DBHelper class is below. Thanks!
Here are images of what the two views look like.
ListView Primary View
Detail View
The MainActivity that contains the first view and the ListView:
public class MainActivity extends AppCompatActivity
{
public final static String ID_EXTRA = "com.example.josh.boergoats._ID";
public final static String NAME_EXTRA = "com.example.josh.boergoats.name";
private DBHelper dbHelper = null;
private Cursor cursor = null;
private DBAdapter adapter = null;
EditText editAnimal = null;
String animalId = null;
long idAnimal = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
editAnimal = (EditText) findViewById(R.id.animalEditText);
dbHelper = new DBHelper(this);
cursor = dbHelper.getAll();
startManagingCursor(cursor);
adapter = new DBAdapter(cursor);
listView.setAdapter(adapter);
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(onSave);
Button deleteButton = (Button) findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(onDelete);
Button editButton = (Button) findViewById(R.id.editButton);
editButton.setOnClickListener(onEdit);
listView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
dbHelper.close();
}
private View.OnClickListener onSave = new View.OnClickListener()
{
public void onClick(View v)
{
Button addButton = (Button) findViewById(R.id.addButton);
if (animalId == null)
{
dbHelper.insert(editAnimal.getText().toString());
}
else
{
dbHelper.update(animalId, editAnimal.getText().toString());
animalId = null;
}
cursor.requery();
editAnimal.setText("");
addButton.setText("Add Animal");
}
};
private View.OnClickListener onDelete = new View.OnClickListener()
{
public void onClick(View v)
{
if (animalId == null)
{
return;
}
else
{
dbHelper.delete(animalId);
animalId = null;
}
cursor.requery();
editAnimal.setText("");
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setText("Add Animal");
}
};
private View.OnClickListener onEdit = new View.OnClickListener()
{
public void onClick(View v)
{
Button editButton = (Button) findViewById(R.id.editButton);
editButton.setVisibility(View.INVISIBLE);
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setText("Add Animal");
Intent i = new Intent(MainActivity.this, DetailActivity.class);
//i.putExtra(ID_EXTRA, String.valueOf(id));
i.putExtra(NAME_EXTRA, String.valueOf(editAnimal.getText().toString()));
i.putExtra(ID_EXTRA, String.valueOf(idAnimal));
editAnimal.setText("");
startActivity(i);
}
};
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
animalId = String.valueOf(id);
Cursor c = dbHelper.getById(animalId);
c.moveToFirst();
editAnimal.setText(dbHelper.getAnimal(c));
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setText("Update");
Button editButton = (Button) findViewById(R.id.editButton);
editButton.setVisibility(View.VISIBLE);
idAnimal = id;
}
};
public class DBAdapter extends CursorAdapter
{
DBAdapter(Cursor c)
{
super(MainActivity.this, c);
}
#Override
public void bindView(View view, Context context, Cursor c)
{
DBHolder holder = (DBHolder) view.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
DBHolder holder = new DBHolder(row);
row.setTag(holder);
return(row);
}
}
static class DBHolder
{
private TextView name = null;
DBHolder(View row)
{
name = (TextView) row.findViewById(R.id.nameTextView);
}
void populateFrom(Cursor c, DBHelper helper)
{
//name.setText(r.getName(c));
name.setText(helper.getAnimal(c));
}
}
}
The second activity, DetailActivity, where I am having the problem.
public class DetailActivity extends AppCompatActivity
{
private DBHelper dbHelper = null;
//private Cursor cursor = null;
String passedName = null;
String passedID = null;
private EditText passedIdView = null;
private EditText passedNameView = null;
private EditText dobView = null;
private EditText commentsView = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//dbHelper = new DBHelper(this);
//cursor = dbHelper.getAllInfo();
passedName = getIntent().getStringExtra(MainActivity.NAME_EXTRA);
passedNameView = (EditText) findViewById(R.id.nameDetailEditText);
passedNameView.setText(passedName);
passedID = getIntent().getStringExtra(MainActivity.ID_EXTRA);
passedIdView = (EditText) findViewById(R.id.idDetailEditText);
passedIdView.setText(passedID);
dobView = (EditText) findViewById(R.id.dobDetailEditText);
commentsView = (EditText) findViewById(R.id.commentsDetailEditText);
Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(onSave);
}
private View.OnClickListener onSave = new View.OnClickListener()
{
public void onClick(View v)
{
String id = passedID;
passedID = getIntent().getStringExtra(MainActivity.ID_EXTRA);
if (passedNameView.getText().toString() != null)
{
if (passedID != null)
{
dbHelper.update(id, passedNameView.getText().toString());
}
}
if (dobView.getText().toString() != null)
{
dbHelper.updateDob(id, dobView.getText().toString());
}
if (commentsView.getText().toString() != null)
{
dbHelper.updateComments(id, commentsView.getText().toString());
}
//reset all edittext fields to blank before leaving
passedIdView.setText("");
passedNameView.setText("");
dobView.setText("");
commentsView.setText("");
Intent i = new Intent(DetailActivity.this, MainActivity.class);
startActivity(i);
}
};
}
The Database Helper class, where the database is created and manipulated. Note that not all of the methods are being used, a few of them are from my experimenting.
public class DBHelper extends SQLiteOpenHelper
{
private static final String dbPath = "/data/data/com.example.josh.boergoats/";
private static final String dbName = "animals.db";
private static final int schemaVersion = 1;
public DBHelper(Context context)
{
super(context, dbName, null, schemaVersion);
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE Animals (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, dob TEXT, comments TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
public void insert(String animal)
{
ContentValues cv = new ContentValues();
cv.put("name", animal);
getWritableDatabase().insert("Animals", "name", cv);
}
public void update(String id, String animal)
{
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("name", animal);
getWritableDatabase().update("Animals", cv, "_id=?", args);
}
public void updateDob(String id, String dob)
{
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("dob", dob);
getWritableDatabase().update("Animals", cv, "_id=?", args);
}
public void updateComments(String id, String comment)
{
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("comments", comment);
getWritableDatabase().update("Animals", cv, "_id=?", args);
}
public void delete(String id)
{
getWritableDatabase().delete("Animals", "_id=?", new String[] {id});
}
public Cursor getAll()
{
return(getReadableDatabase().rawQuery("SELECT _id, name FROM Animals", null));
}
public Cursor getAllInfo()
{
return(getReadableDatabase().rawQuery("SELECT _id, name, dob, comments FROM Animals", null));
}
public String getAnimal(Cursor c)
{
return(c.getString(1));
}
public String getDob(Cursor c)
{
return(c.getString(2));
}
public String getComments(Cursor c)
{
return(c.getString(3));
}
public Cursor getById(String id)
{
String[] args = {id};
return(getReadableDatabase().rawQuery("SELECT _id, name FROM Animals WHERE _id=?", args));
}
}
Thank you again in advance.
What I do, to use the same activity to add or edit (which I believe is what you're trying to do), is to pass, via an Intent Extra, the respective option and then have the code set the respective values. here's an example :-
String caller = getIntent().getStringExtra("Caller");
if(getIntent().getStringExtra("Caller").equals("ShopListByCursorActivityUpdate")) {
((EditText) findViewById(R.id.ase_storename_input)).setText(getIntent().getStringExtra("ShopName"));
((EditText) findViewById(R.id.ase_storeorder_input)).setText(getIntent().getStringExtra("ShopOrder"));
((EditText) findViewById(R.id.ase_storestreet_input)).setText(getIntent().getStringExtra("ShopStreet"));
((EditText) findViewById(R.id.ase_storecity_input)).setText(getIntent().getStringExtra("ShopCity"));
((EditText) findViewById(R.id.ase_storestate_input)).setText(getIntent().getStringExtra("ShopState"));
((EditText) findViewById(R.id.ase_storephone_input)).setText(getIntent().getStringExtra("ShopPhone"));
((EditText) findViewById(R.id.ase_storenotes_input)).setText(getIntent().getStringExtra("ShopNotes"));
setTitle(getResources().getString(R.string.title_activity_shop_edit));
}
The 2nd Line checks for the Update mode (ie what is in the Intent Extra named Caller (extracted into caller)) and then sets the respective values which themselves are in Intent Extras. 1st line isn't needed I just had it there for debugging purposes.
Note the when called by Edit as opposed to Add then the Intent Extra Caller is set to ShopListByCursorActivityUpdate when adding is is set to ShopListByCursorActivity.
PS You may have issues in the first activity not displaying the changed/saved data as it doesn't appear that you refresh the data. In brief, if this is an issue. You need to rebuild the cursor (ie redo the query) and then get the adapter to use the new/amended cursor via changeCursor, SwapCursor or notifyDataSetChanged. eg :-
Cursor csr = shopperdb.getShopsAsCursor();
currentsca.swapCursor(csr);
In regards to comment
You are on the right track, but I was actually having trouble putting the information that I needed into the Intent Extra. Since I don't have the DOB or comments field on my first activity, I need to pull that information from my database and put it into the Intent Extra somehow. Those 2 fields are created in my DBHelper class. Also, depending on how they can be pulled from the database, they may not even need to be put in the Intent Extra if they can be put straight into my EditTexts.
Then Use SELECT * FROM Animals to get all columns in getAll then all columns will be available in the returned Cursor.

Update Database Entry Displayed in Fragment Listview by Dialog

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;
}
});

Categories

Resources