Update Database Entry Displayed in Fragment Listview by Dialog - android

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

Related

Data are not deleted from database

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

How to show SQLite database data in a recylerview list which is inside a fragment?

I am an amateur android developer and I would like to get user entered items from the database and then display it in a recyclerview list (not ListView) that is in a fragment.
So far I have already created the SQLite database which saves the data into it, I just want to know I can display all this information in the recyclerview. The Java code shown below shows what I want to make but is in a listview instead of a recyclerview.
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "budget10.db";
public static final String TABLE_NAME = "expense_table";
public static final String TABLE_NAME2 = "income_table";
public static final String COL_1 = "_id";
public static final String COL_2 = "_id";
public static final String EXPENSE_AMOUNT = "EXPENSE_AMOUNT";
public static final String EXPENSE_DATE = "DATE";
public static final String EXPENSE_NOTES = "NOTES";
public static final String INCOME_AMOUNT = "INCOME_AMOUNT";
public static final String INCOME_DATE = "DATE";
public static final String INCOME_NOTES = "NOTES";
public static final String INCOME_CATEGORY = "INCOME_CATEGORY";
public static final String EXPENSE_CATEGORY = "EXPENSE_CATEGORY";
public static final String EXPENSE_ACCOUNT = "EXPENSE_ACCOUNT";
public static final String INCOME_ACCOUNT = "INCOME_ACCOUNT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, EXPENSE_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, EXPENSE_CATEGORY TEXT, EXPENSE_ACCOUNT TEXT)");
db.execSQL("create table " + TABLE_NAME2 + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,INCOME_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, INCOME_CATEGORY TEXT, INCOME_ACCOUNT TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
onCreate(db);
}
public boolean insertexpenseData(Double amount_expense, String date_expense, String notes_expense, String category_expense, String expense_account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EXPENSE_AMOUNT, amount_expense);
contentValues.put(EXPENSE_DATE, date_expense);
contentValues.put(EXPENSE_NOTES, notes_expense);
contentValues.put(EXPENSE_CATEGORY, category_expense);
contentValues.put(EXPENSE_ACCOUNT, expense_account);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean insertincomeData(Double amount_income, String date_income, String notes_income, String category_income, String income_account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INCOME_AMOUNT, amount_income);
contentValues.put(INCOME_DATE, date_income);
contentValues.put(INCOME_NOTES, notes_income);
contentValues.put(INCOME_CATEGORY, category_income);
contentValues.put(INCOME_ACCOUNT, income_account);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getexpenseData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Cursor getincomeData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME2, null);
return res;
}
public boolean updateexpenseData(String id, String amount, String date, String notes, String catagory_income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(EXPENSE_AMOUNT, amount);
contentValues.put(EXPENSE_DATE, date);
contentValues.put(EXPENSE_NOTES, notes);
contentValues.put(EXPENSE_CATEGORY, catagory_income);
db.update(TABLE_NAME, contentValues, "_id = ?", new String[]{id});
return true;
}
public boolean updateincomeData(String id, String amount, String date, String notes, String catagory_income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, id);
contentValues.put(INCOME_AMOUNT, amount);
contentValues.put(INCOME_DATE, date);
contentValues.put(INCOME_NOTES, notes);
contentValues.put(INCOME_CATEGORY, catagory_income);
db.update(TABLE_NAME2, contentValues, "_id = ?", new String[]{id});
return true;
}
public Integer deleteexpenseData(String _id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "_id = ?", new String[]{_id});
}
public Integer deleteincomeData(String _id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME2, "_id = ?", new String[]{_id});
}
public double getNetBudget() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) - (SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table) FROM income_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netBudget = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netBudget = cursor.getDouble(0);
}
cursor.close();
return netBudget;
}
public double getTotalExpense() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netExpense = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netExpense = cursor.getDouble(0);
}
cursor.close();
return netExpense;
}
public double getTotalIncome() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) FROM income_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netIncome = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netIncome = cursor.getDouble(0);
}
cursor.close();
return netIncome;
}
public void deleteAllIncome() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME2, null, null);
db.execSQL("delete from " + TABLE_NAME2);
db.close();
}
public void deleteAllExpense() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
db.execSQL("delete from " + TABLE_NAME);
db.close();
}
}
Fragment ListView that I want to turn into a recyclerview
public class tab2income extends Fragment {
private static final String TAG = "tab2income";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
View rootView;
Cursor incomedata;
SimpleCursorAdapter sca;
DecimalFormat formatter = new DecimalFormat("0.00");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab2income, container, false);
return rootView;
}
#Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) rootView.findViewById(R.id.listViewincome);
mListView.setEmptyView(rootView.findViewById(R.id.empty));
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
incomedata = mDatabaseHelper.getincomeData();
sca = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, incomedata, new String[]{DatabaseHelper.INCOME_AMOUNT}, new int[]{android.R.id.text1}, 0);
mListView.setAdapter(sca);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
l,
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
incomedata.close();
}
public void displayNoteDate(String noteContent, String dateValue,String category, final long noteID,String account) {
MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
.title("Income Information")
.content("Date: "+ dateValue+
"\nCategory: "+category+
"\nAccount: "+account+
"\nNote: "+noteContent)
.positiveText("close")
.negativeText("delete")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
mDatabaseHelper.deleteincomeData(Long.toString(noteID));
incomedata = mDatabaseHelper.getincomeData();
sca.swapCursor(incomedata);
}
});
builder.show();
}
}
EDIT
This is what I have done so far with the code in the answer from Saurov Bagchi and I have the recyclerview in my xml file and nothing happens when an item is clicked:
Fragment
public class tab2income extends Fragment implements ItemClickListener {
private static final String TAG = "tab2income";
DatabaseHelper mDatabaseHelper;
private RecyclerView mListView;
View rootView;
Cursor incomedata;
SimpleCursorAdapter sca;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab2income, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = rootView.findViewById(R.id.ListViewincome);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mListView.setLayoutManager(layoutManager);
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
MyAdapter myAdapter = new MyAdapter(arrayList);
mListView.setAdapter(myAdapter);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
} while (incomedata.moveToNext());
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onDestroy() {
super.onDestroy();
incomedata.close();
}
#Override
public void onClick(View view, int i) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
public void displayNoteDate(String noteContent, String dateValue,String category,String account) {
MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
.title("Income Information")
.content("Date: "+ dateValue+
"\nCategory: "+category+
"\nAccount: "+account+
"\nNote: "+noteContent)
.positiveText("close")
.negativeText("delete")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
});
builder.show();
}
}
Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private ItemClickListener clickListener;
public MyAdapter(ArrayList<String> myDataset) {
dataSet = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//layout of the list item
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(dataSet.get(position));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
ViewHolder(View v) {
super(v);
//textview for showing results
mTextView = v.findViewById(android.R.id.text1);
v.setOnClickListener(this);
}
//for click
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
For RecyclerView you need to create your own custom Adapter.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private ItemClickListener clickListener;
public MyAdapter(ArrayList<String> myDataset) {
dataSet = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//layout of the list item
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(dataSet.get(position));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
ViewHolder(View v) {
super(v);
//textview for showing results
mTextView = v.findViewById(android.R.id.text1);
v.setOnClickListener(this);
}
//for click
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
Then I am just rewriting the populateListView() method
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
MyAdapter myAdapter = new MyAdapter(arrayList);
mListView.setAdapter(myAdapter);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
} while (incomedata.moveToNext());
}
myAdapter.notifyDataSetChanged();
}
You also need to create an Interface for each Item Click.
public interface ItemClickListener {
void onClick (View view, int position);
}
And implement this Interface in your Fragment.
public class tab2income extends Fragment implements ItemClickListener{
//All of your codes
#Override
public void onClick (View view, int i) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
l,
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
}

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

ListView adding first item multiple times

So I have a ListView and a custom adapter for it
I am adding valued to the database and then repopulating the list
so I added items in the following way : q, w,e,r,t,y,u,i,o,p
the listview populated as follows : q,w,e,r,t,y,q,q,q
This is the custom adapter
public class TestListAdapter extends BaseAdapter {
private static ArrayList<FlashCard> flashCardItems;
private LayoutInflater mInflater;
private Context context;
public TestListAdapter(Context context, ArrayList<FlashCard> results) {
this.context = context;
flashCardItems = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return flashCardItems.size();
}
public Object getItem(int position) {
return flashCardItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.flashcard, null);
holder = new ViewHolder();
holder.flipper = (ViewFlipper) convertView.findViewById(R.id.flashcard);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.flipper.addView(FlashCard.createQuestionCard(context,flashCardItems.get(position).getQuestion()));
return convertView;
}
static class ViewHolder {
ViewFlipper flipper;
}
}
This is the Database Handler
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "mySchoolDB";
// Flashcards table name
private static final String TABLE_FLASHCARDS = "flashcards";
// Flashcards Table Columns names
private static final String KEY_ID = "id";
private static final String QUESTION = "question";
private static final String ANSWER = "answer";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FLASHCARDS_TABLE = "CREATE TABLE " + TABLE_FLASHCARDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + QUESTION + " TEXT,"
+ ANSWER + " TEXT" + ")";
db.execSQL(CREATE_FLASHCARDS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FLASHCARDS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new Flashcard
public void addFlashcard(FlashCard flashcard) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(QUESTION, flashcard.getQuestion()); // flashcard Name
values.put(ANSWER, flashcard.getAnswer()); // flashcard Phone
// Inserting Row
db.insert(TABLE_FLASHCARDS, null, values);
db.close(); // Closing database connection
}
// Getting single FlashCard
public FlashCard getFlashcard(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_FLASHCARDS, new String[] { KEY_ID,
QUESTION, ANSWER }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
FlashCard flashcard= new FlashCard(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
cursor.close();
db.close();
// return FlashCard
return flashcard;
}
// Getting All Flashcards
public ArrayList<FlashCard> getAllFlashcards() {
ArrayList<FlashCard> FlashcardList = new ArrayList<FlashCard>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_FLASHCARDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FlashCard flashcard = new FlashCard(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2));
// Adding Flashcard to list
FlashcardList.add(flashcard);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return Flashcard list
return FlashcardList;
}
// Updating single Flashcard
public int updateFlashcard(FlashCard flashcard) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(QUESTION, flashcard.getQuestion());
values.put(ANSWER, flashcard.getAnswer());
db.close();
// updating row
return db.update(TABLE_FLASHCARDS, values, KEY_ID + " = ?",
new String[] { String.valueOf(flashcard.getID()) });
}
// Deleting single Flashcard
public void deleteFlashcard(FlashCard flashcard) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_FLASHCARDS, KEY_ID + " = ?",
new String[] { String.valueOf(flashcard.getID()) });
db.close();
}
// Getting Flashcards Count
public int getFlashcardsCount() {
String countQuery = "SELECT * FROM " + TABLE_FLASHCARDS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void deleteAllFlashCards(){
SQLiteDatabase sdb= this.getWritableDatabase();
sdb.delete(TABLE_FLASHCARDS, null, null);
sdb.close();
}
}
and this is the listview
public class TestList extends ListView
{
private Context context;
private ArrayList<FlashCard> stringArray = new ArrayList<FlashCard>();
public TestList(Context context) {
super(context);
this.context = context;
setResults();
}
public void setResults() {
DatabaseHandler db = new DatabaseHandler(context);
stringArray = db.getAllFlashcards();
setAdapter(new TestListAdapter(context, stringArray));
}
public TestList(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void addFlashCardDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Add flashcard");
final EditText question = new EditText(context);
question.setHint("Question");
final EditText answer = new EditText(context);
answer.setHint("Answer");
LinearLayout qa = new LinearLayout(context);
qa.setOrientation(LinearLayout.VERTICAL);
qa.addView(question);
qa.addView(answer);
builder.setView(qa);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FlashCard f = new FlashCard(question.getText().toString(), answer.getText().toString());
DatabaseHandler db = new DatabaseHandler(context);
db.addFlashcard(f);
setResults();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
addView() isn't replacing the view that currently exists. When the convertView comes back to be recycled, 'q' already exists inside the ViewFlipper, and you want q to go away and be replaced by 'u'
holder.flipper.addView(FlashCard.createQuestionCard(context,flashCardItems.get(position).getQuestion()));
Try setting the view inside the view flipper to the new value instead of using addView().
Example:
TextView text = (TextView) ViewFlipper.findViewById(R.id.textView);
text.setText(flashCardItems.get(position).getQuestion());
the problem is coming from the ViewFlipper you're using in your adapter.
List views in android use view recycling (which is what the convertView is for in getView) but due to how you're handling them every time a view gets recycled you add another view to the flipper, what you need to do is add the view when convertView is null and then modify the view in the flipper to represent your data, not sure how the question card view works so I'm just guessing there.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.flashcard, null);
holder = new ViewHolder();
holder.flipper = (ViewFlipper) convertView.findViewById(R.id.flashcard);
holder.card = FlashCard.createQuestionCard(context,flashCardItems.get(position).getQuestion());
holder.filpper.addView(holder.card);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.card.setQuestion(flashCardItems.get(position).getQuestion());
return convertView;
}
obviously you'll have to adjust your view holder and add a card field with the proper type and add a setQuestion method to the questionCard view but you get the idea.

SQL table not found exception

i have made a table and its fields but i get error that no such row exist and if i comment them out then it is not detecting the table also showing no such table exist.Here's the code:
package com.example.ifest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper{
private static final String DB_NAME = "event_db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "_table";
private static final String EVENT_NAME = "_name" ;
private static final String EVENT_ID = "_no" ;
private static final String EVENT_TYPE = "_type" ;
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ EVENT_NAME + " TEXT NOT NULL, " + EVENT_TYPE + " TEXT NOT NULL);" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
and the code for my other acitvity is:
public class ProfileView extends ListActivity{
String e,e1;
static int p = 0;
Spinner spn ;
Button b1,b2;
EditText et;
String str1;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("Create");
openDB();
p++;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(position == 0){
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition());
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
}
}
protected void addDB(String name,int id) {
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_name",name);
if(id == 0)
cv.put("type","WIFI");
else if(id == 1)
cv.put("type","BLUETOOTH");
else if(id == 2)
cv.put("type","MEDIA");
db.insert("_table", null , cv);
db.close();
}
private void openDB() {
if(p != 0){
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+ "event_db",null);
c.moveToFirst();
while(c.moveToNext()){
list.add(c.getString(1));
Log.d("cursor", c.getString(1));
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.string_main,menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition());
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
break;
case R.id.item2:
break;
case R.id.item3:
Intent i = new Intent("com.example.ifest.ABOUTUS");
startActivity(i);
break;
case R.id.item4:
finish();
break;
}
return true;
}
}
You are using "type" on your contentvalue but your column is named: "_type".
You are querying the event_db table which is the name of your database, not your table
Cursor c = db.rawQuery("SELECT * FROM "+ "event_db",null);
You should query the _table table
Cursor c = db.rawQuery("SELECT * FROM "+ "_table",null);
By the way it would be more clear if you name your database db (I doubt you need more than one db anyway) and your table _event (you can have many tables and you should name them accordingly to their role and not just _table)

Categories

Resources