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.
Related
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());
I am trying to delete objects in a listView and database at the same time after you have clicked the item in the listView. I'm tying to make it open an alert dialog before deleting the item. I have read many other stack overflow questions about this such as :
how can i delete an item from listview and also database
delete a specific item from listview stored in database in android application
Delete item from database - ListView - Android
And many others...none of them I find very helpful. Any suggestions?
Main_Activity:
public class New_Recipe extends AppCompatActivity {
Button add, done;
EditText Recipe_Name, Recipe_Item, Recipe_Steps;
String search;
WebView webView;
DatabaseHelper databaseHelper;
ListView ItemsList;
Context context = this;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
RecipeListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new__recipe);
setTitle("New Recipe");
add = (Button) findViewById(R.id.button2);
done = (Button) findViewById(R.id.button);
Recipe_Name = (EditText) findViewById(R.id.editText);
Recipe_Item = (EditText) findViewById(R.id.editText2);
Recipe_Steps = (EditText) findViewById(R.id.editText3);
webView = (WebView) findViewById(R.id.webView);
ItemsList = (ListView) findViewById(R.id.listView);
listAdapter = new RecipeListAdapter(getApplicationContext(), R.layout.recipe_textview);
context = this;
AddData();
}
//When the add button is pressed
public void AddData() {
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = Recipe_Item.getText().toString();
databaseHelper = new DatabaseHelper(context);
sqLiteDatabase = databaseHelper.getWritableDatabase();
databaseHelper.addItems(item, sqLiteDatabase);
Toast.makeText(getBaseContext(), "Item inserted", Toast.LENGTH_LONG).show();
databaseHelper.close();
ItemsList.setAdapter(listAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getItems(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String items;
items = cursor.getString(0);
RecipeDataProvider dataProvider = new RecipeDataProvider(items);
listAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
}
});
}
public void onSearch(View v) {
search = "Recipes";
webView.loadUrl("https://www.google.com/search?q=" + search);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new__recipe, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 5;
public static final String DATABASE_NAME = "Recipes.db";
public static final String CREATE_QUERRY = "create table " + RecipeContract.RecipeEntry.TABLE_NAME + "( _ID INTEGER PRIMARY KEY, NAME text, ITEMS text, STEPS text)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Recipe Database", "Database should be made!");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERRY);
Log.d("Recipe Database", "Table should be made!");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addItems(String items, SQLiteDatabase db)
{
ContentValues values = new ContentValues();
values.put(RecipeContract.RecipeEntry.COL2,items);
db.insert(RecipeContract.RecipeEntry.TABLE_NAME,null,values);
Log.e("Recipe Database","Item should be added to the table!");
}
public Cursor getItems(SQLiteDatabase db)
{
Cursor cursor;
String[] projections = {RecipeContract.RecipeEntry.COL2};
cursor = db.query(RecipeContract.RecipeEntry.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
ListViewAdapter:
public class RecipeListAdapter extends ArrayAdapter {
List list = new ArrayList();
public RecipeListAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView ITEM;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.recipe_textview,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.ITEM = (TextView) row.findViewById(R.id.tx_items);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
RecipeDataProvider dataProvider = (RecipeDataProvider) this.getItem(position);
layoutHandler.ITEM.setText(dataProvider.getItems().toString());
return row;
}
EDIT: my updated Main_Activity class
public class New_Recipe extends AppCompatActivity {
Button add, done;
EditText Recipe_Name, Recipe_Item, Recipe_Steps;
String search;
WebView webView;
DatabaseHelper databaseHelper;
ListView ItemsList;
Context context = this;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
RecipeListAdapter listAdapter;
List<New_Recipe> list = new ArrayList<>();
private int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new__recipe);
setTitle("New Recipe");
add = (Button) findViewById(R.id.button2);
done = (Button) findViewById(R.id.button);
Recipe_Name = (EditText) findViewById(R.id.editText);
Recipe_Item = (EditText) findViewById(R.id.editText2);
Recipe_Steps = (EditText) findViewById(R.id.editText3);
webView = (WebView) findViewById(R.id.webView);
ItemsList = (ListView) findViewById(R.id.listView);
listAdapter = new RecipeListAdapter(getApplicationContext(), R.layout.recipe_textview);
context = this;
AddData();
ItemsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Object getSelectedItem = list.get(position);
databaseHelper.deleteItem(getSelectedItem);
listAdapter.deleteitem(getSelectedItem);
return true;
}
});
}
public New_Recipe(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
You can use this method for deleting a row from DatabaseHelper class :
public void deleteItem(Object item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[]{String.valueOf(item.getId())});
db.close();
}
And then you need also one method for deleting object from adapter :
public void deleteItem(Object item) {
listArray.remove(item);
notifyDataSetChanged();
}
Now you can call all this method in activity like this :
Let's say that you want to delete all this by clicking long on list item :
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
Object getSelectedItem = arrayList.get(pos);
dataBaseHelper.deleteItem(getSelectedItem);
adapter.deleteItem(getSelectedItem);
return true;
}
});
UPDATED:
You need before you try to call method getId() to create that method in your class. So you need to create get and setter methods in your class, something like this:
STEP BY STEP:
Change your class New_Recipe to MainActivity. If you are getting an error, just highlight that error and there you will see "rename file".
Create a new class outside your main class and call it NewRecipe:
public class NewRecipe {
private int id;
private String title;
public NewRecipe() {
// empty constructor
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
And now you can do everything i have explained earlier.
You need a function deletein DatabaseHelper class
public boolean delete(long rowId) {
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
You need a function in the Activity deleteItem() similar to addItems()
public void deleteItem(){
//Based on some logic,find the rowID of the table which needs to be deleted and call delete function of DatabaseHelper class.
}
Similarily in your ListViewAdapter, you need to define a method delete
public void delete(Object object) {
list.remove(object);
//To update the ListView in Android
this.notifyDataSetChanged();
}
After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}
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)));
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