Searching particular record from custom ListView - android

I have stored three values into the database and i want to make search on button click, after clicking on search button it will be move on search screen and there is only search box is presented.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DATABASENAME = "Aadhaar";
public static String PRODUCTTABLE = "Enrolled";
private ArrayList<CandidateModel> cartList = new ArrayList<CandidateModel>();
Context c;
public DatabaseHelper(Context context) {
super(context, DATABASENAME, null, 33);
c = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE if not exists Enrolled(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "_id"
+ " TEXT ,"
+ "FirstName"
+ " TEXT,"
+ "LastName"
+ " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE);
onCreate(db);
}
public void addProduct(CandidateModel productitem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("_id", productitem.idno);
contentValues.put("FirstName", productitem.productname);
contentValues.put("LastName", productitem.productprice);
db.insert("Enrolled", null, contentValues);
db.close();
}
// update
public void updateProduct(CandidateModel productList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FirstName", productList.productname);
contentValues.put("LastName", productList.productprice);
db.update("Enrolled", contentValues, "_id=" + productList.idno, null);
db.close();
}
public void emptyProduct() {
try {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from Enrolled");
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeProduct(String productid, String pname, String pprice) {
try {
// SQLiteDatabase db = this.getWritableDatabase();
// db.execSQL("delete from producttable where productidno="
// + productid);
// db.close();
String[] args = { productid };
getWritableDatabase().delete("Enrolled", "_id=?", args);
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<CandidateModel> getProudcts() {
cartList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from Enrolled", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
CandidateModel item = new CandidateModel();
item.idno = cursor.getString(cursor.getColumnIndex("_id"));
item.productname = cursor.getString(cursor
.getColumnIndex("FirstName"));
item.productprice = cursor.getString(cursor
.getColumnIndex("LastName"));
cartList.add(item);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}
}
Aadhar.java
public class Aadhar extends Activity implements OnClickListener {
private Button btn_add, btn_view, btn_search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_add = (Button) findViewById(R.id.btn_add);
btn_view = (Button) findViewById(R.id.btn_view);
btn_search = (Button) findViewById(R.id.btn_search);
btn_add.setOnClickListener(this);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Intent addintent = new Intent(Aadhar.this, AddRecord.class);
startActivity(addintent);
break;
case R.id.btn_view:
Intent viewintent = new Intent(Aadhar.this, ViewRecord.class);
startActivity(viewintent);
break;
case R.id.btn_search:
Intent searchIntent = new Intent (Aadhar.this, SearchRecord.class);
startActivity(searchIntent);
default:
break;
}
}
}
SearchRecord.java
public class SearchRecord extends Activity implements OnClickListener {
String TAG = "SearchRecord";
private ListView lv;
// Button searchButton;
private EditText search;
CandidateModel cm;
DatabaseHelper db;
public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_candidate);
Log.v(TAG, "Searching Candidates");
lv = (ListView) findViewById(R.id.search_listview);
search = (EditText) findViewById(R.id.edit_search);
Log.v(TAG, "Going to enter into TextWatcher");
lv.setTextFilterEnabled(true);
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.v(TAG, "Entered into the Text Changed Method");
((Filterable) _candidatelist).getFilter().filter(s.toString());
Log.v(TAG, "Finished Filtering");
lv.setAdapter((android.widget.ListAdapter) _candidatelist);
}
});
}
CandidateModel.java
public class CandidateModel {
public String getFirstname() {
return fname;
}
public void setFirstname(String fname) {
this.fname = fname;
}
public String getLastname() {
return lname;
}
public void setLastname(String lname) {
this.lname = lname;
}
public String idno="", fname="", lname="";
public String getIdno() {
return idno;
}
public void setIdno(String idno) {
this.idno = idno;
}
}
ViewRecord.java
public class ViewRecord extends Activity {
private ListView listview;
// private EditText search;
String TAG = "ViewRecord";
TextView totalrecords;
DatabaseHelper db;
public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_candidates);
totalrecords = (TextView) findViewById(R.id.totalrecords);
listview = (ListView) findViewById(R.id.listview);
}
#Override
protected void onResume() {
super.onResume();
_candidatelist.clear();
db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<CandidateModel> cand_list = db.getCandidates();
for (int i = 0; i < cand_list.size(); i++) {
String tidno = cand_list.get(i).getIdno();
System.out.println("tidno>>>>>" + tidno);
String tname = cand_list.get(i).getFirstname();
String tprice = cand_list.get(i).getLastname();
CandidateModel _CandidateModel = new CandidateModel();
_CandidateModel.setIdno(tidno);
_CandidateModel.setFirstname(tname);
_CandidateModel.setLastname(tprice);
_candidatelist.add(_CandidateModel);
}
totalrecords.setText("Total Enrollments :-" + _candidatelist.size());
listview.setAdapter(new ListAdapter(this));
db.close();
}
public class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return _candidatelist.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
viewHolder = new ViewHolder();
viewHolder._id = (TextView) convertView
.findViewById(R.id.txtdisplaypname);
viewHolder.fname = (TextView) convertView
.findViewById(R.id.txtdisplaypprice);
viewHolder.lname = (TextView) convertView
.findViewById(R.id.txtdisplaypid);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder._id.setText(_candidatelist.get(position).getFirstname()
.trim());
viewHolder.fname.setText(_candidatelist.get(position).getLastname()
.trim());
viewHolder.lname.setText(_candidatelist.get(position).getIdno()
.trim());
final int temp = position;
(convertView.findViewById(R.id.btn_update))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String _id = String.valueOf(_candidatelist
.get(temp).getIdno());
String _fname = _candidatelist.get(temp)
.getFirstname();
String _lname = _candidatelist.get(temp)
.getLastname();
Intent intent = new Intent(ViewRecord.this,
AddUpdateValues.class);
Bundle bundle = new Bundle();
bundle.putString("id", _id);
bundle.putString("name", _fname);
bundle.putString("price", _lname);
intent.putExtras(bundle);
startActivity(intent);
}
});
(convertView.findViewById(R.id.btn_delete))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewRecord.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Log.i(">>>TEMP>>>", temp + "");
Log.i(">>>getIdno>>>>>>",
_candidatelist.get(temp)
.getIdno().trim()
+ "");
System.out
.println(">>>getIdno>>>>>>"
+ _candidatelist
.get(temp)
.getIdno()
.trim());
db.removeCandidate(
_candidatelist.get(temp)
.getIdno().trim(),
"", "");
ViewRecord.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
});
return convertView;
}
}
public class ViewHolder {
TextView _id;
TextView fname;
TextView lname;
}
}

ArrayList is not Filterable. It says in the Filterable documentation :
Defines a filterable behavior. A filterable class can have its data
constrained by a filter. Filterable classes are usually Adapter
implementations.
I think you should replace your ArrayList by an ArrayAdapter

Related

Delete ListiView and SQLite row in Android

I'm developing an application in Android Studio using this library: com.daimajia.swipelayout:library:1.2.0#aar. My app user a SQLite database with the following classes:
BDSQLiteHelper.java
public class BDSQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ExtraOficial";
private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";
private static final String vazID = "VazID";
private static final String nomeServico = "nomeServico";
private static final String[] VAZ_COLUNAS = {vazID, nomeServico};
public BDSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
"vazID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"nomeServico)";
db.execSQL(CREATE_VAZAMENTOTABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
this.onCreate(db);
}
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeServico, VazamentosToSQL.getNomeServico());
db.insert(TABELA_VAZAMENTOS, null, values);
db.close();
}
public VazamentosToSQL getVazamentos (int vazID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELA_VAZAMENTOS,
VAZ_COLUNAS,
" vazID = ?",
new String[] {String.valueOf(vazID)},
null,
null,
null,
null);
if (cursor == null) {
return null;
} else {
cursor.moveToFirst();
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
return VazamentosToSQL;
}
}
private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
VazamentosToSQL.setNomeServico(cursor.getString(1));
return VazamentosToSQL;
}
public ArrayList<VazamentosToSQL> getAllVazamentos() {
ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
listaVazamentos.add(VazamentosToSQL);
} while (cursor.moveToNext());
}
return listaVazamentos;
}
[...]
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS,
vazID+" =?",
new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
VazamentosToSQL.java
public class VazamentosToSQL {
private int vazID;
private String nomeServico;
public int getVazID() { return vazID; }
public void setVazID(int vazID) {
this.vazID = vazID;
}
public String getNomeServico() { return nomeServico; }
public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }
}
ListViewActivity.java:
[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
[...]
bd = new BDSQLiteHelper(this);
lista = (ListView) findViewById(R.id.lvdenuncias);
listaVazamentos = bd.getAllVazamentos();
setListViewHeader();
setListViewAdapter();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
startActivity(intent);
}
});
#Override
protected void onStart() {
super.onStart();
updateAdapter(); //Refresh ListView items
}
private void setListViewHeader() {
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview, lista, false);
totalClassmates = (TextView) header.findViewById(R.id.total);
swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
setSwipeViewFeatures();
//UNNECESSARY for me: lista.addHeaderView(header);
}
private void setSwipeViewFeatures() {
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
//add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
Log.i(TAG, "onClose");
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
Log.i(TAG, "on swiping");
}
#Override
public void onStartOpen(SwipeLayout layout) {
Log.i(TAG, "on start open");
}
#Override
public void onOpen(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally show");
}
#Override
public void onStartClose(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally close");
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
}
private void setListViewAdapter() {
adapter = new vazamentosAdapter(this, listaVazamentos);
lista.setAdapter(adapter);
}
public void updateAdapter() {
listaVazamentos.clear();
listaVazamentos.addAll(bd.getAllVazamentos());
adapter.notifyDataSetChanged(); //update adapter
lista.invalidateViews();
lista.refreshDrawableState();
}
}
vazamentosAdapter.java:
public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
private final Context context;
private final ArrayList<VazamentosToSQL> elementos;
File imgFile;
private Bitmap bitmap;
private ExifInterface exifObject;
private ExibeVazamentosActivity activity;
int vazID;
private SQLiteDatabase bd;
public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
super(context, R.layout.linha, elementos);
this.context = context;
this.elementos = elementos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.linha, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
}else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
[...]
editText.setText(elementos.get(position).getVaznomeServico());
holder.btnEdit.setOnClickListener(onEditListener(position, holder));
holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));
return convertView;
}
private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
/**--------------Tried it, not working =( ---------------*/
elementos.get(position).getVazID();
//listaVazamentos.remove(position);
//activity.listaVazamentos.remove(position);
//bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
//bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
//bd.close();
//elementos.remove(position);
Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
bd.deleteVazamentos(VazamentosToSQL);
holder.swipeLayout.close();
// activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
/**--------------Tried it, not working =( ---------------*/
}
};
}
private class ViewHolder {
private TextView name;
private View btnDelete;
private View btnEdit;
private SwipeLayout swipeLayout;
private ListView listv;
public ViewHolder(View v) {
swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
btnDelete = v.findViewById(R.id.delete);
btnEdit = v.findViewById(R.id.edit_query);
listv = (ListView) v.findViewById(R.id.lvdenuncias);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
The mentioned library is working great. But i'm trying to delete database row when user click in a button according to the listview selected line. With this code: elementos.get(position).getVazID() I get the database index. But I can't delete from database. Someone can help me with the code to delete row from database and line from listview?
Try changing this:
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
To this:
public void deleteVazamentos(int vazID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null);
}
Then if you want to delete a row, you can call:
(Inside onDeleteListener)
bd.deleteVazamentos(elementos.get(position).getVazID());

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

How to remove an item in an SQL database? [duplicate]

This question already has answers here:
Deleting Row in SQLite in Android
(18 answers)
Closed 6 years ago.
I know there are lots of threads with more or less same topic but none of them covers my situation:
I have delete button that delete one item in a listView but when you close the app and reopen it the items reappears. I don't know how to fix this .
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final int DATABASE_VERSION = 1;
public static final String ITEMS_TABLE = "items";
private static DatabaseHelper instance = null;
public static DatabaseHelper getInstance(Context context) {
if(instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE " + ITEMS_TABLE + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"description TEXT NOT NULL, " +
"completed INTEGER NOT NULL DEFAULT 0)";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
The button works fine but it does not delete permently I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
private ToDoItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
adapter.swapItems(listManager.getList());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
private LayoutInflater inflater;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
this.inflater = LayoutInflater.from(context);
}
public void swapItems(List<ToDoItem> items) {
this.items = items;
notifyDataSetChanged();
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ItemViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
holder = new ItemViewHolder();
holder.itemDescription = (TextView) convertView.findViewById(R.id.item);
holder.itemState = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
}else {
holder = (ItemViewHolder) convertView.getTag();
}
holder.itemDescription.setText(items.get(position).getDescription());
holder.itemState.setChecked(items.get(position).isComplete());
holder.itemState.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) holder.itemState.getTag();
item.toggleComplete();
listManager.updateItem(item);
notifyDataSetChanged();
}
});
ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
notifyDataSetChanged();
}
});
holder.itemState.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ToDoItem item = (ToDoItem) holder.itemState.getTag();
item.toggleComplete();
listManager.updateItem(item);
notifyDataSetChanged();
}
});
return convertView;
}
}
public static class ItemViewHolder{
public TextView itemDescription;
public CheckBox itemState;
}
}
ToDoListManager.java
public class ToDoListManager {
private DatabaseHelper dbHelper;
public ToDoListManager(Context context) {
dbHelper = DatabaseHelper.getInstance(context);
}
public List<ToDoItem> getList() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DatabaseHelper.ITEMS_TABLE,
null
);
List<ToDoItem> items = new ArrayList<>();
if(cursor.moveToFirst()) {
while(!cursor.isAfterLast()) {
ToDoItem item = new ToDoItem(
cursor.getString(cursor.getColumnIndex("description")),
cursor.getInt(cursor.getColumnIndex("completed")) != 0,
cursor.getLong(cursor.getColumnIndex("_id"))
);
items.add(item);
cursor.moveToNext();
}
}
cursor.close();
return items;
}
public void addItem(ToDoItem item) {
ContentValues newItem = new ContentValues();
newItem.put("description", item.getDescription());
newItem.put("completed", item.isComplete());
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.insert(DatabaseHelper.ITEMS_TABLE, null, newItem);
}
public void updateItem(ToDoItem item) {
ContentValues editItem = new ContentValues();
editItem.put("description", item.getDescription());
editItem.put("completed", item.isComplete());
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] args = new String[] { String.valueOf(item.getId()) };
db.update(DatabaseHelper.ITEMS_TABLE, editItem, "_id=?", args);
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
private long id;
public ToDoItem(String description, boolean isComplete) {
this(description, isComplete, -1);
}
public ToDoItem(String description,boolean isComplete,long id) {
this.description = description;
this.isComplete = isComplete;
this.id = id;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
public long getId() {return id;}
#Override
public String toString() {
return getDescription();
}
}
you just remove items in your adapter class that causes the item delete from the current listView. but you have not any function in your ToDoListManager.java that remove items from your database. deleting from a listView does not affect to your database items.
you can add this function to your ToDoListManager.java class
public void deleteItem(long itemId) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(DatabaseHelper.ITEMS_TABLE, "_id = ?",
new String[] { String.valueOf(itemId) });
}
and call it from your delete button's onClick, like this
ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long itemId = items.get(position).getId();
items.remove(items.get(position));
listManager.deleteItem(itemId);
notifyDataSetChanged();
}
});
Since you are fetching the data from data base and displaying it in listview,you need to delete the row from database too. make a method in you database adapter that looks some thing like this:
public boolean deleteItem(Long id) {
return Db.delete(DATABASE_TABLE,"_id="+id,null) > 0;
}
then on list view item delete,simply call this method and pass the row id as argument.

Android Database shows same value again and again

In my android database based app.When i retrieve data from database it got the same value(first value inserted into database) again and again. what is the problem?
Inserting data class
public class MainActivity extends AppCompatActivity {
public String dataBase_Name="database";
public static DatabaseHelper database;
private TextView text;
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper database1=new DatabaseHelper(this,dataBase_Name);
database=database1;
Button add=(Button)findViewById(R.id.button);
text=(TextView)findViewById(R.id.editText);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp=text.getText().toString();
database.insert(temp);
text.setText("");
}
});
Button next=(Button) findViewById(R.id.button6);
Button prev=(Button) findViewById(R.id.button4);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Delete.class);
MainActivity.this.startActivity(intent);
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, com.example.partha.app4.View.class);
MainActivity.this.startActivity(intent);
}
});
}
}
Retrieving class
public class View extends MainActivity {
private GestureDetector gestureDetector;
private android.view.View.OnTouchListener gestureListener;
ArrayAdapter<String> adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
listView = (ListView) findViewById(R.id.listView);
String[] load = database.get_all_entry();
String[] temp=database.get_all_entry();
Toast.makeText(this,"Length "+temp.length,Toast.LENGTH_LONG);
for(int i=0;i<temp.length;i++)
{
Toast.makeText(this,temp[i],Toast.LENGTH_SHORT);
}
if (load != null) {
adapter = new ArrayAdapter<String>(this, R.layout.item,R.id.textView, database.get_all_entry());
listView.setAdapter(adapter);
} else {
Toast.makeText(this, "Data cant found", Toast.LENGTH_SHORT);
}
Button next = (Button) findViewById(R.id.button11);
Button prev = (Button) findViewById(R.id.button10);
next.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
clear();
Intent intent = new Intent(View.this, MainActivity.class);
View.this.startActivity(intent);
}
});
prev.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
clear();
Intent intent = new Intent(View.this, Update.class);
View.this.startActivity(intent);
}
});
} catch (Exception e) {
Log.e("view", e.toString());
}
}
void clear()
{
listView.setAdapter(null);
}
}
Databasehelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
public static String databaseName;
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
Context context1;
DatabaseHelper(Context context,String databaseName)
{
super(context,databaseName,null,1);
this.databaseName=databaseName;
context1=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table contacts" + "(" + CONTACTS_COLUMN_ID + " integer primary key,name text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insert(String name)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("name", name);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public boolean update (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("contacts", contentValues, "id = ? ", new String[]{Integer.toString(id)});
return true;
}
public int find(String name)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query("contacts", new String[]{"name"}, "name = ?", new String[]{name}, null, null, null);
cursor.moveToFirst();
if((cursor!=null)&&(cursor.getCount()!=0)) {
int id = cursor.getInt(cursor.getColumnIndex(CONTACTS_COLUMN_ID));
return id;
}
else
{
return -1;
}
}
public Integer delete (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public String[] get_all_entry()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query("contacts",null,null,null,null,null,null);
cursor.moveToFirst();
if((cursor!=null)&&(cursor.getCount()!=0))
{
String []name=new String[cursor.getCount()];
for(int i=0;i<cursor.getCount();i++)
{
name[i]=(cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_NAME)));
}
return name;
}
else
{
return null;
}
}
}
you are missing cursor.moveToNext(); in your loop at get_all_entry()
so you are filling the array items with the same cursor record (first record) after calling cursor.moveToFirst();
modify your for loop as following:
for(int i=0;i<cursor.getCount();i++){
name[i]=(cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_NAME)));
cursor.moveToNext(); // <---- ADD THIS
}
P.S: consider using while(cursor.moveToNext()){} to read your cursor records, i think it's better than using for loop

Listview empty after insert a field in db?

I was looking for an example/tutorial to insert datas in a sqlLite db and display the datas in a listview. Well this is a good example: http://androidsolution4u.blogspot.it/2013/09/android-populate-listview-from-sqlite.html And it works. I implemented the code in mine and works. The problem is that if i want insert another one filed nothing appears in the listview and the activity is empty.I added a field called address as string like the others and in every part of code i added what is need copying from the others (of course changing the names). But when i try to add the item not appears. Of course i update the xml files with new field. I can't write the whole code because it's too much. But if someone can help me to find a way out i'll write the part of code required. Thanks
EDIT: the code is equal at the example but with the field i need to add.
The DisplayActivity
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_address = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("address", user_address.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2) + " " + user_address(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ user_address.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_address.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName, user_address);
userList.setAdapter(disadpt);
mCursor.close();
}
}
The DisplayAdapter
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> address;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> address) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.address = address;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_address = (TextView) child.findViewById(R.id.txt_address);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_address.setText(address.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_address;
}
}
The DbHelper
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_ADDRESS="address";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_ADDRESS+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
And the AddActivity
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,edit_address;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,address;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
edit_address=(EditText)findViewById(R.id.address_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
address=getIntent().getExtras().getString("address");
edit_first.setText(fname);
edit_last.setText(lname);
edit_address.setText(address);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
address=edit_address.getText().toString().trim();
if(fname.length()>0 && lname.length()>0 && address.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_ADDRESS,address );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
That's all. I can't find the problem. Helps?
Forgotten in displayData() user_address.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ADDRESS)));

Categories

Resources