Hello I have SQLite application based on SQLite database and I want it to have search/filter option. When i tried to use
adapter.getFilter().filter(query)
It filtered, but after filtering once,i can't do any more actions(add or delete items). Maybe someone have ideas how can I make search ?
DBAdapter.java
static final String ROW_ID ="id";
static final String NAME ="name";
static final String TAG = "DBAdapter";
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context ctx) {
this.c = ctx;
helper = new DBHelper(c);
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DBAdapter","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
public DBAdapter openDB()
{
try {
db=helper.getWritableDatabase();
} catch (SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
public void close()
{
helper.close();
}
public long add(String name)
{
try {
ContentValues cv = new ContentValues();
cv.put(NAME,name);
return db.insert(TBNAME,ROW_ID,cv);
} catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames()
{
String[] columns={ROW_ID,NAME};
return db.query(TBNAME,columns,null,null,null,null,null);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lv;
EditText nameTxt;
Button savebtn,retrievebtn;
ArrayList<String> books = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt=(EditText)findViewById(R.id.editText);
savebtn=(Button)findViewById(R.id.saveBtn);
retrievebtn=(Button)findViewById(R.id.retrieveBtn);
lv = (ListView)findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item,books);
final DBAdapter db = new DBAdapter(this);
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.openDB();
long result = db.add(nameTxt.getText().toString());
if(result > 0)
{
nameTxt.setText("");
}else
{
Toast.makeText(getApplicationContext(),"Failure", Toast.LENGTH_SHORT).show();
}
db.close();
}
});
retrievebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
books.clear();
db.openDB();
Cursor c = db.getAllNames();
while (c.moveToNext())
{
String colIndex = c.getString(1);
books.add(colIndex);
}
lv.setAdapter(adapter);
db.close();
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),books.get(position), Toast.LENGTH_SHORT).show();
}
});
}
Related
i want to delete item from a listView and SQLite database with contextMenu (press on item and hold, delete button appears, press it and item deletes) and my code doesnt remove anything. I tried when pressed on Delete, toast with text appears and it worked.
DBAdapter.java
public void delete(String name)throws SQLException {
SQLiteDatabase db = helper.getWritableDatabase();
if (db == null) {
return;
}
String[] whereArgs = new String[] { name };
db.delete("m_TB", "NAME"+ "=?", whereArgs);
db.close();
}
MainActivity.java
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("Delete");
}
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String name = info.toString();
if (item.getTitle().equals("Delete")) {
db.delete(name);
books.remove(item);
adapter.notifyDataSetChanged();
}
return true;
}
FULL CODE:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lv;
EditText nameTxt;
Button savebtn, retrievebtn;
ArrayList<String> books = new ArrayList<String>();
ArrayAdapter<String> adapter;
SearchView sv;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
final DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt = (EditText) findViewById(R.id.editText);
savebtn = (Button) findViewById(R.id.saveBtn);
retrievebtn = (Button) findViewById(R.id.retrieveBtn);
lv = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, books);
registerForContextMenu(lv);
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.openDB();
long result = db.add(nameTxt.getText().toString());
if (result > 0) {
nameTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
db.close();
}
});
retrievebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
books.clear();
db.openDB();
Cursor c = db.getAllNames();
while (c.moveToNext()) {
String colIndex = c.getString(1);
books.add(colIndex);
}
lv.setAdapter(adapter);
db.close();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), books.get(position), Toast.LENGTH_SHORT).show();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("Delete");
}
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String name = info.toString();
if (item.getTitle().equals("Delete")) {
books.remove(info.position);
adapter.notifyDataSetChanged();
}
return true;
}
}
DBAdapter.java
public class DBAdapter {
static final String ROW_ID ="id";
static final String NAME ="name";
static final String TAG = "DBAdapter";
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context ctx) {
this.c = ctx;
helper = new DBHelper(c);
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DBAdapter","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
public DBAdapter openDB()
{
try {
db=helper.getWritableDatabase();
} catch (SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
public void close()
{
helper.close();
}
public long add(String name)
{
try {
ContentValues cv = new ContentValues();
cv.put(NAME,name);
return db.insert(TBNAME,ROW_ID,cv);
} catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames()
{
String[] columns={ROW_ID,NAME};
return db.query(TBNAME,columns,null,null,null,null,null);
}
public void delete(String name)throws SQLException
{
SQLiteDatabase db = helper.getWritableDatabase();
if(db == null)
{
return;
}
String[] whereArgs = new String[]{name};
db.delete("m_TB", "NAME"+ "=?", whereArgs);
db.close();
}
}
You are not removing the item from the list books. If books is an ArrayList then
Change your line of code to
books.remove(info.position);
And to remove from database (If books is an ArrayList of custom type).
db.delete(books.get(info.position).name);
And if books is an arraylist of string then
db.delete(books.get(info.position));
In my android database based app.When i retrieve data from database it got the same value(first value inserted into database) again and again. what is the problem?
Inserting data class
public class MainActivity extends AppCompatActivity {
public String dataBase_Name="database";
public static DatabaseHelper database;
private TextView text;
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper database1=new DatabaseHelper(this,dataBase_Name);
database=database1;
Button add=(Button)findViewById(R.id.button);
text=(TextView)findViewById(R.id.editText);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp=text.getText().toString();
database.insert(temp);
text.setText("");
}
});
Button next=(Button) findViewById(R.id.button6);
Button prev=(Button) findViewById(R.id.button4);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Delete.class);
MainActivity.this.startActivity(intent);
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, com.example.partha.app4.View.class);
MainActivity.this.startActivity(intent);
}
});
}
}
Retrieving class
public class View extends MainActivity {
private GestureDetector gestureDetector;
private android.view.View.OnTouchListener gestureListener;
ArrayAdapter<String> adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
listView = (ListView) findViewById(R.id.listView);
String[] load = database.get_all_entry();
String[] temp=database.get_all_entry();
Toast.makeText(this,"Length "+temp.length,Toast.LENGTH_LONG);
for(int i=0;i<temp.length;i++)
{
Toast.makeText(this,temp[i],Toast.LENGTH_SHORT);
}
if (load != null) {
adapter = new ArrayAdapter<String>(this, R.layout.item,R.id.textView, database.get_all_entry());
listView.setAdapter(adapter);
} else {
Toast.makeText(this, "Data cant found", Toast.LENGTH_SHORT);
}
Button next = (Button) findViewById(R.id.button11);
Button prev = (Button) findViewById(R.id.button10);
next.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
clear();
Intent intent = new Intent(View.this, MainActivity.class);
View.this.startActivity(intent);
}
});
prev.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
clear();
Intent intent = new Intent(View.this, Update.class);
View.this.startActivity(intent);
}
});
} catch (Exception e) {
Log.e("view", e.toString());
}
}
void clear()
{
listView.setAdapter(null);
}
}
Databasehelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
public static String databaseName;
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
Context context1;
DatabaseHelper(Context context,String databaseName)
{
super(context,databaseName,null,1);
this.databaseName=databaseName;
context1=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table contacts" + "(" + CONTACTS_COLUMN_ID + " integer primary key,name text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insert(String name)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("name", name);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public boolean update (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("contacts", contentValues, "id = ? ", new String[]{Integer.toString(id)});
return true;
}
public int find(String name)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query("contacts", new String[]{"name"}, "name = ?", new String[]{name}, null, null, null);
cursor.moveToFirst();
if((cursor!=null)&&(cursor.getCount()!=0)) {
int id = cursor.getInt(cursor.getColumnIndex(CONTACTS_COLUMN_ID));
return id;
}
else
{
return -1;
}
}
public Integer delete (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public String[] get_all_entry()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query("contacts",null,null,null,null,null,null);
cursor.moveToFirst();
if((cursor!=null)&&(cursor.getCount()!=0))
{
String []name=new String[cursor.getCount()];
for(int i=0;i<cursor.getCount();i++)
{
name[i]=(cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_NAME)));
}
return name;
}
else
{
return null;
}
}
}
you are missing cursor.moveToNext(); in your loop at get_all_entry()
so you are filling the array items with the same cursor record (first record) after calling cursor.moveToFirst();
modify your for loop as following:
for(int i=0;i<cursor.getCount();i++){
name[i]=(cursor.getString(cursor.getColumnIndex(CONTACTS_COLUMN_NAME)));
cursor.moveToNext(); // <---- ADD THIS
}
P.S: consider using while(cursor.moveToNext()){} to read your cursor records, i think it's better than using for loop
The spinner has items that are dynamically added with two editText's and a Button. When the user inputs text into the first EditText it displays that text in the spinner. I am trying to Toast KEY_CALORIES from the second EditText that is sent into the database with OnItemSelected. I am trying to learn as a hobby so, an explanation would be great.
MainActivity. At the bottom is the OnItemSelected.
public class MainActivity extends Activity implements OnItemSelectedListener {
Button AddBtn;
EditText et;
EditText cal;
Spinner spn;
SQLController SQLcon;
ProgressDialog PD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AddBtn = (Button) findViewById(R.id.addbtn_id);
et = (EditText) findViewById(R.id.et_id);
cal = (EditText) findViewById(R.id.et_cal);
spn = (Spinner) findViewById(R.id.spinner_id);
spn.setOnItemSelectedListener(this);
SQLcon = new SQLController(this);
// opening database
SQLcon.open();
loadtospinner();
AddBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new MyAsync().execute();
}
});
}
public void loadtospinner() {
Cursor c = SQLcon.readData();
ArrayList<String> al = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(DBhelper.MEMBER_NAME));
al.add(name);
c.moveToNext();
}
ArrayAdapter<String> aa1 = new ArrayAdapter<String>(
getApplicationContext(), R.layout.spinner_item, R.id.textView1,
al);
spn.setAdapter(aa1);
// closing database
SQLcon.close();
al.add("Shit");
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
String name = et.getText().toString();
String calories = cal.getText().toString();
// opening database
SQLcon.open();
// insert data into table
SQLcon.insertData(name, calories);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
loadtospinner();
PD.dismiss();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
/* I am trying to Toast KEY_CALORIES from the database
* Tried many solution that failed and can't seem to grasp retrieving a single item from the database.
* Appreciate your help
*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
DataBase
public class SQLController {
private DBhelper dbhelper;
private Context ourcontext;
private SQLiteDatabase database;
public SQLController(Context c) {
ourcontext = c;
}
public SQLController open() throws SQLException {
dbhelper = new DBhelper(ourcontext);
database = dbhelper.getWritableDatabase();
return this;
}
public void close() {
dbhelper.close();
}
public void insertData(String name, String calories) {
ContentValues cv = new ContentValues();
cv.put(DBhelper.MEMBER_NAME, name);
cv.put(DBhelper.KEY_CALORIES, calories);
database.insert(DBhelper.TABLE_MEMBER, null, cv);
}
public Cursor readData() {
String[] allColumns = new String[] { DBhelper.MEMBER_ID,
DBhelper.MEMBER_NAME, DBhelper.KEY_CALORIES };
Cursor c = database.query(DBhelper.TABLE_MEMBER, allColumns, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
Helper
public class DBhelper extends SQLiteOpenHelper {
// TABLE INFORMATTION
public static final String TABLE_MEMBER = "member";
public static final String MEMBER_ID = "_id";
public static final String MEMBER_NAME = "name";
public static final String KEY_CALORIES = "calories";
// DATABASE INFORMATION
static final String DB_NAME = "MEMBER.DB";
static final int DB_VERSION = 2;
// TABLE CREATION STATEMENT
private static final String CREATE_TABLE = "create table " + TABLE_MEMBER
+ "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MEMBER_NAME + " TEXT NOT NULL," + KEY_CALORIES
+ " INT NOT NULL);";
public DBhelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
onCreate(db);
}
}
Edit It is Toasting the cal but every single cal entered into the database any suggestion to just show the cal that is clicked?
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
/*
* I am trying to Toast KEY_CALORIES Tried many solution that failed and
* can't seem to grasp retrieving a single item from the database.
* Appreciate your help
*/
SQLcon.open();
Cursor c = SQLcon.readData();
c.moveToFirst();
while (!c.isAfterLast()) {
String cal= c.getString(c.getColumnIndex(DBhelper.KEY_CALORIES));
Toast.makeText(getBaseContext(), cal+ "", Toast.LENGTH_LONG)
.show();
c.moveToNext();
}
SQLcon.close();
// closing database
}
First you need access to your adapter in order to get the selected string, so I would declare the aa1 adapter as a class field.
When you do that, you can access your adapter from the onItemSelected method:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
String your_selected_item=(String)aa1.getItem(pos);
Toast.makeText(getApplicationContext(),
your_selected_item, Toast.LENGTH_SHORT).show();
}
But I think your approach is not right... If you are listing DB-stored data, you should take a look at the CursorAdapter ;)
I put some code together to have functionality of updating my sql rows but it doesn't work. Can anyone have a look at my code please and let me know where I am wrong?
I can post alternative code if necessary. Here is my dialog file which is supposed to update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
// public EditListItemDialog(Context context, List<String> fragment_monday) { //first constructor
// super(context);
// this.fragment_monday = fragment_monday;
// }
#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);
}
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;
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
adapter.notifyDataSetChanged();
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 1);
dba.close();
((TextView) editText).setText("");// TODO Auto-generated method stub
}
}
MyDB file:
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;
}
}
dba object is not initialized and your try/catch get the crash. Initialize it with
dba = new MyDB(context);
in your EditListItemDialog constructor (Uncomment it and remove List fragment_monday) like this:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
Replace your saveItToDB method with:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 1);
dba.close();
((TextView) editText).setText("")
}
dba.open() is missing.
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