I would like to add a feature that would allow me to remove a row from my recyclerview/database.
This feature is integrate to each item of my recyclerview as show in the following picture :
MySQLite.java:
public class MySQLite extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "character";
private static final int DATABASE_VERSION = 1;
private static final String CHARACTER_TABLE = "Ichar";
private static final String CHAR_TABLE = "create table " + CHARACTER_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT, nom TEXT, prenom TEXT , numero TEXT)";
Context context;
public MySQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CHAR_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void InsererBDD(String nom, String prenom, String numero) {
Log.d("insert", "before insert");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues entree = new ContentValues();
entree.put("nom", nom);
entree.put("prenom", prenom);
entree.put("numero", numero);
db.insert(CHARACTER_TABLE, null, entree);
db.close();
Toast.makeText(context, "insérer entrée", Toast.LENGTH_LONG);
Log.i("insert", "after insert");
db.close();
}
public List<Character> donneesBDD() {
List<Character> modelList = new ArrayList<Character>();
String query = "select * FROM " + CHARACTER_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Character model = new Character();
model.setCharacter_Id(cursor.getInt(0));
model.setNom(cursor.getString(1));
model.setPrenom(cursor.getString(2));
model.setNumero(cursor.getString(3));
modelList.add(model);
} while (cursor.moveToNext());
}
Log.d("donnee character", modelList.toString());
return modelList;
}
public void supprimerLigne(int character_Id){
SQLiteDatabase db = getWritableDatabase();
db.delete(CHARACTER_TABLE , "id" + " = ?", new String[] { String.valueOf(character_Id)});
db.close();
}
public Character getCharacterById(int Id) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " +
"nom" + "," +
"prenom" + "," +
"numero" +
" FROM " + CHARACTER_TABLE
+ " WHERE " +
"id" + "=?";
Character character = new Character();
Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(Id)});
if (cursor.moveToFirst()) {
do {
character.character_Id = cursor.getInt(cursor.getColumnIndex("id"));
character.nom = cursor.getString(cursor.getColumnIndex("nom"));
character.prenom = cursor.getString(cursor.getColumnIndex("prenom"));
character.numero = cursor.getString(cursor.getColumnIndex("numero"));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return character;
}
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
static List<Character> characters;
static Context context;
MyAdapter(Context context,List<Character> characters)
{
this.characters = new ArrayList<Character>();
this.context = context;
this.characters = characters;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int itemType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_cell, null);
MyViewHolder myViewHolder = new MyViewHolder(itemLayoutView);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
holder.nom.setText(characters.get(position).getNom());
holder.prenom.setText(characters.get(position).getPrenom());
}
#Override
public int getItemCount() {
return characters.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener,View.OnClickListener, MenuItem.OnMenuItemClickListener {
public TextView nom;
public TextView prenom;
public ImageButton delete;
public MyViewHolder(final View itemLayoutView) {
super(itemLayoutView);
nom = ((TextView) itemLayoutView.findViewById(R.id.nom));
prenom = ((TextView) itemLayoutView.findViewById(R.id.prenom));
delete = (ImageButton) itemView.findViewById(R.id.delete);
itemLayoutView.setOnClickListener(this);
itemLayoutView.setOnCreateContextMenuListener(this);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(getAdapterPosition());
}
});
}
#Override
public void onClick(View view) {
Intent intent = new Intent(context, personne.class);
Bundle extras = new Bundle();
extras.putInt("position", getAdapterPosition());
intent.putExtras(extras);
context.startActivity(intent);
Toast.makeText(MyAdapter.context, "Vous avez sélectionné un item" + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("");
menu.add(0, v.getId(), 0, "Modifier Contact");
menu.add(0, v.getId(), 0, "Supprimer Contact");
}
#Override
public boolean onMenuItemClick(MenuItem item)
{
return true;
}
}
}
can you guide me?
Thanks a lot.
You need to remove the item from your array and then notifyDataSetChanged()
fragmentOrActivity.yourArray.remove(holder.getAdapterPosition());
fragmentOrActivity.yourAdapter.notifyDataSetChanged();
Hope that helps :-)
You should write your code in onBindViewHolder method like below.
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(characters.get(position).getId());
}
});
Related
my app stores name and result in SQLite database and displays that in RecycleViewer. Previously I use a listView where on LongClick I could delete an item like here LuckyNumbersApk/commit/4cec554359662d557626935046b8de68fb1b5c60
now I have switched to recyclerView I can't handle it properly. When I delete it, it disapears but when I reload the fragment the deleted entry reappears again. I assume it because the item is deleted only from the list in the adapter but how can I delete it from the list that is in the fragment that actually calls the recylerViewer?
This is my Adapter:
public class DatabaseAdapter extends RecyclerView.Adapter {
List dataModelArrayList;
Context context;
public DatabaseAdapter(List<DataModel> dataModelArrayList, Context context) {
this.dataModelArrayList = dataModelArrayList;
this.context = context;
}
class Myholder extends RecyclerView.ViewHolder implements CardView.OnLongClickListener {
TextView name, result;
public Myholder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.card_name);
result = (TextView) itemView.findViewById(R.id.card_result);
CardView cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_warning_black_24dp)
.setTitle("Delete result")
.setMessage("Are you sure you want delete this result?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* This is where deletions should be handled */
int id = getAdapterPosition();
DataBHelper database = new DataBHelper(context);
database.deleteEntry(id);
dataModelArrayList.remove(id);
notifyItemRemoved(id);
notifyDataSetChanged();
database.close();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
}
#Override
public int getItemCount() {
return dataModelArrayList.size();
}}
This is DataBHelper:
public class DataBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "results_database";
public static final String RESULTS_TABLE_NAME = "results_table";
public static final String RESULTS_COLUMN_ID = "_id";
public static final String RESULTS_COLUMN_NAME = "name";
public static final String RESULTS_COLUMN_RESULT = "result";
public DataBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " (" +
RESULTS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RESULTS_COLUMN_NAME + " TEXT, " +
RESULTS_COLUMN_RESULT + " TEXT" + ")");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RESULTS_TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void saveToDB(String fname, String lname, String result) {
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
String name = fname + " " + lname;
values.put(DataBHelper.RESULTS_COLUMN_NAME, name);
values.put(DataBHelper.RESULTS_COLUMN_RESULT, result);
database.insert(DataBHelper.RESULTS_TABLE_NAME, null, values);
database.close();
}
public List<DataModel> readDB(){
List<DataModel> data=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+RESULTS_TABLE_NAME+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel= new DataModel();
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String result = cursor.getString(cursor.getColumnIndexOrThrow("result"));
dataModel.setName(name);
dataModel.setResult(result);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
public void clearDatabase() {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String clearDBQuery = "DELETE FROM "+RESULTS_TABLE_NAME;
sqLiteDatabase.execSQL(clearDBQuery);
}
public void deleteEntry(long row) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.delete(RESULTS_TABLE_NAME, RESULTS_COLUMN_ID + "=" + row, null);
}}
And this is the fragment which loads recyclerViewer
public class ResultsFragment extends Fragment {
DataBHelper database;
RecyclerView recyclerView;
DatabaseAdapter recycler;
public List<DataModel> datamodel;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_results,
container, false);
datamodel =new ArrayList<DataModel>();
recyclerView = (RecyclerView) view.findViewById(R.id.app_recycle_view);
database = new DataBHelper(getActivity());
datamodel = database.readDB();
recycler = new DatabaseAdapter(datamodel, getActivity());
RecyclerView.LayoutManager reLayoutManager =new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(reLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recycler);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
if (datamodel.isEmpty()) {
recyclerView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
}
return view;
}}
In onCreateViwHolder:
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
holder.id = dataModel.getId();
}
Add long id; into the ViewHolder, so your onClick you can delete the int id = getAdapterPosition(); and the id will be the id from the model.
To remove still use the adapter position:
dataModelArrayList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
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);
}
}
Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.
I have created an application that a user can store player information. I am now looking to have a checkbox to confirm that the player is available. I know that sqlite cannot store a boolean value so was wondering if someone could help me with a way around this. I have added the checkbox but at the moment i have it stored as a 0 value with no functionality.
Below is the display adapter:
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email;
//private ArrayList<String> ConFirm;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
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_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
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_eMail.setText(Email.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
Here is the display call from the main activity:
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_eMail.clear();
user_cOnfirm.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)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And finally the Dbhelper:
public class DbHelper extends SQLiteOpenHelper {
public 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_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
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_EMAIL+" TEXT, "+KEY_CONFIRM+" TEXT DEFAULT 0)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
If you would like any more information or code just let me know. Thankyou in advance.
------UPDATED------
Below is the db update function from the FoursFragment.java class:
//add
view.findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//Update
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("Confirm", user_cOnfirm.get(arg2));
i.putExtra("Mail", user_eMail.get(arg2));
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//delete
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
build = new AlertDialog.Builder(getActivity());
build.setTitle("Delete " + user_fName.get(arg2) + " "
+ user_lName.get(arg2) + " " + user_eMail.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(
getActivity(),
user_fName.get(arg2) + " "
+ user_lName.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;
}
});
return view;
}
}}
#Override
public void onResume() {
displayData();
super.onResume();
}
//display
#SuppressLint("UseValueOf")
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_eMail.clear();
user_cOnfirm.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)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
At first you should change your database table. Don't use the type 'TEXT' to store the boolean, use the type 'TINYINT' instead of that. TINYINT provides 1 byte to save the value. Because of that you can define a constraint (the check at the end), to avoid saving values like 3.
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
To read the value from the database change the loop.
while(mCursor.moveToNext()) {
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)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
You request an Integer instead of a String as returning value from the database. If you need to get a boolean, you can add the comparision with 1.
Just a tip, you don't need your do-while. The cursor points at the beginning on a position before the first entry. With the call of moveToNext for the first time, you move it to the first entry. If there's no entry, the loop will be skipped.
You need to change the type of the ArrayList to Boolean (with a big B).
Add the initialization with the value for the checkbox
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos));
These are the necessary changes. I add the changed code below (not tested)
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email; // better name it email
private ArrayList<Boolean> ConFirm; //better name it confirm, it's one word
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
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; // the m shows that this shall be a member variable, this is just local for this method.
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_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
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_eMail.setText(Email.get(pos));
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos).booleanValue());
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
The part from your main activity
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_eMail.clear();
user_cOnfirm.clear();
while(mCursor.moveToNext()) {
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)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And your DBHelper
public class DbHelper extends SQLiteOpenHelper {
public 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_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 2); // The 2 is the version. It have to be higher than the old, because we changed the database schema
}
#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_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
I hope this solves your problem, if not feel free to ask another question, if please rate this answer as positive.
P.s.:
Take a look at the coding guidelines: https://source.android.com/source/code-style.html
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