Android Listview onListItemClick get Sqlite Id - android

I am simply displaying a list from sqlite table. I have not used any BDHelper class. With this code only how can i get id.
When i click on 1st Item, it shows 0 where as in table it's id is 1. Below is my code.
SQLiteDatabase myDB;
try {
myDB = openOrCreateDatabase(DB_NAME,
SQLiteDatabase.CREATE_IF_NECESSARY, null);
myDB.execSQL("create table if not exists " + COUNTRY_TABLE
+ "(country_id INTEGER PRIMARY KEY,"
+ "country_title text,"
+ "country_status int(11));");
/*myDB.execSQL("insert into " + COUNTRY_TABLE +" values "+
"(null,'India',1)," +
"(null,'China',1)," +
"(null,'Australia',1)," +
"(null,'Japan',1)," +
"(null,'Germany',1)");*/
Cursor c = myDB.rawQuery("select country_id,country_title from "
+ COUNTRY_TABLE + " where country_status=1", null);
if (c != null) {
if (c.moveToFirst()) {
do {
int id = c.getInt(c.getColumnIndex("country_id"));
String name = c.getString(c.getColumnIndex("country_title"));
clist.add(id + ") " + name);
} while (c.moveToNext());
//int itemcount = clist.size();
//Toast.makeText(MainActivity.this, itemcount, Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, clist));
}
}
} catch (SQLiteException se) {
Toast.makeText(MainActivity.this, se.getMessage().toString(),Toast.LENGTH_LONG).show();
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(MainActivity.this,String.valueOf(id),Toast.LENGTH_LONG).show();
}
Please suggest what should i do to get the id fron table and not the position.

try below code:
Put your id and name data in clist ArrayList, generate getter, setter method first, set your id and name in that method when myou get that data, each time add that data in ArrayList and then use it like below.
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(MainActivity.this,clist.get(position).getId(),Toast.LENGTH_LONG).show();
}

public List<Emp> AllRecords()
{
List<Emp> dataset = new ArrayList<Emp>();
Cursor cursor = database.query(DatabaseHelper.TABLE_EMPLOYEE,allColumns, null, null,null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Emp obj = cursorToContact(cursor);
dataset.add(obj);
cursor.moveToNext();
}
cursor.close();
return dataset;
}
private Emp cursorToContact(Cursor cursor)
{
Emp obj = new Emp();
obj.setId(cursor.getInt(0));
obj.setName(cursor.getString(1));
obj.setDesig(cursor.getString(2));
return obj;
}
//--------------
list_data = (ArrayList<Emp>) qh.AllRecords();
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,list_data);
//---------
int id=list_data.get(arg2); //Type mismatch: cannot convert from Emp to int
Plz tell what should i write to get country id.

Seeing as how there is no accepted answer...
I did this and it seemed to work.
I'm using a ListView Activity, SQLiteDatabase and an ArrayAdapter
In my onListItemClick method, I instantiate a new object and make it equal to whatever item is at that current position in my adapter.
Task task = adapter.getItem(arg3);
In my task class, I have a private variable of type long called id, as well as a setter and getter for that variable.
Hence, I can then do this:
long taskId = task.getId();
Checking this result with Toast yielded the id generated by SQLite NOT the position in the ListView, which is what I needed.
Hope this helps someone out!

you can set tag on list item with the id after which you can call getTag() on onItemClick.

((TextView)v).getText(); by using this we will get the text of view, then we can query to the table again to get id of the corresponding text and toast it.
String country_title=((TextView)v).getText();
Cursor c = myDB.rawQuery("select country_id from "+ COUNTRY_TABLE + " where country_title='"+country_title+"'", null);
Toast.makeText(MainActivity.this,c.getString(c.getColumnIndexorThrow("country_title")),Toast.LENGTH_LONG).show();

This was not possible the way i wanted it but got its solution some other way. While in cursor loop, adding data to list, take another ArrayList and add only id to it.
clist1.add(id);
Now, on onListItemClick, you can get the position of the item. So, use this position and get the id from the other ArrayList clist1
int country_id=clist1[position];
Hope this helps.

I'm a couple years late, but it might help someone else: basically set the tag wherever you're setting the individual views.
// Find fields to populate in inflated template
TextView productName = (TextView) view.findViewById(R.id.product_name);
TextView productPrice = (TextView) view.findViewById(R.id.product_price);
TextView productQuantity = (TextView) view.findViewById(R.id.product_quantity);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_NAME));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_PRICE));
int quantity = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_QUANTITY));
int id = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.ID));
// Set Tag
productName.setTag(id);
and then later you can access it by calling on getTag():
int id = (Integer)((TextView)findViewById(R.id.product_name)).getTag();
Log.d("LETSEE",String.valueOf(id));

Related

delete zero index of listview which populated from database Android

My Database class is this, when i call deleteEntry, it does not remove 0 index , this is database class method
public int deleteEntry(String id)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
//String id=String.valueOf(ID);
String where="ID=?";
int numberOFEntriesDeleted= db.delete("TIME", where, new String[]{id}) ;
Toast.makeText(context, "Number of Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
this is my onItemClickListener
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item id", " " + id);
// data.remove(id);
String row = (String.valueOf(id));
data.deleteEntry(row);
You can try like this:
//---deletes a particular entry---
public int deleteEntry(String id)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
return db.delete("TIME", "ID = " + id, null) ;
}
By the way, make sure "TIME" is your tablename and you also close the database.
here is what I did
consider i have two tables and so a dynamic listview with two items (i.e with a custom adapter)
I delete items by name (You can get the name of a selected item at position
Yourlist.setOnItemLongClickListener(new OnItemLongClickListener() { #Override public boolean onItemLongClick(AdapterView arg0, View arg1, int arg2, long id) {
String str = Yourlist.getItemAtPosition(arg2).toString();
//consider i have two tables
        //create a table called feedslist with a column called "url" where items (the feeds urls) will be stored
        mydb.execSQL("CREATE TABLE IF NOT EXISTS feedslist (id INTEGER PRIMARY KEY AUTOINCREMENT,url varchar);");
        //create a table called subtitles list with a column called "name" where items (the feeds names) will be stored
        mydb.execSQL("CREATE TABLE IF NOT EXISTS subtitleslist (id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar);");
        
//this is the method to delete entries
alert.setPositiveButton(R.string.deleteok, new DialogInterface.OnClickListener() {
                    #Override
                    public void onClick(DialogInterface dialog, int which) {
                        //on positive click we delete the feed from selected position
                        //we're gonna delete them from the db
                        //using cursor
                        Cursor cursor =mydb.rawQuery("SELECT * FROM feedslist;", null);
                        Cursor cursor2 =mydb.rawQuery("SELECT * FROM subtitleslist;", null);
                        String url = "";
                        String name = "";
                        //set url
                        if (cursor != null && cursor.moveToFirst()) {
                            while (!cursor.isAfterLast()) {
                                //we get items at selected position
                                url = mItems.get(datposition);
                                cursor.moveToNext();
                            }
                            cursor.close();
                        }
                        //set feed name
                        if (cursor2 != null && cursor2.moveToFirst()) {
                            while (!cursor2.isAfterLast()) {
                                //we get items at selected position
                                name = mItems2.get(datposition);
                                cursor2.moveToNext();
                            }
                            cursor2.close();
                        }
                        //set the names of the two tables
                        String table1 = "feedslist";
                        String table2 = "subtitleslist";
                        //set where clause
                        String whereClause_url = "url" + "=?";
                        String whereClause_feed = "name" + "=?";
                        //set the where arguments
                        String[] whereArgs_url = new String[] { String.valueOf(url) };
                        String[] whereArgs_name = new String[] { String.valueOf(name) };
                        //delete 'em all
                        mydb.delete(table1, whereClause_url, whereArgs_url);
                        mydb.delete(table2, whereClause_feed, whereArgs_name);
                        //remove items from the dynamic listview
                        //for url
                        mItems.remove(datposition);
                        //for feed name
                        mItems2.remove(datposition);
                        //and update the dynamic list
                        //don't move this method above the db deletion method or
                        //you'll get javalangindexoutofboundsexception-invalid-index error
                        adapter_dynamic.notifyDataSetChanged();
                        adapter_dynamic.notifyDataSetInvalidated();
                        listfeed.setAdapter(adapter_dynamic);
 
You can see working app here
https://github.com/enricocid/iven-feed-reader
Try passing the position instead of an id:
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item id", " " + id);
Log.d("Clicked item position", " " + position);
String row = (String.valueOf(position)); // the change is here
data.deleteEntry(row);
}
After you try this, look at the logs you get and try to figure out which value (id or position) are better. Anyway, I suppose you should store the database ID of each item you are displaying somewhere, so that you will not rely only on the position inside your list (once any item is deleted from your table, this will not work) since the ID's will not be sequential.

Android : How to create Cursor object to get item id in SQLite?

How to create cursor object to get item id from database?
Here is my method of DBHelper, see the Cursor method
public int getItemIdByPosition(int position) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToPosition(position);
return Integer.parseInt(cursor.getString(0));
}
Seems to be correct.
Maybe the position passed through method is not correct, maybe is more efficient is you use, instead of pass a position on your method pass the ID:
"select * from " + TABLE_NAME + " where id = " = id
Also you can use:
cursor.getColumnIndex(COLUMN_NAME) instead of cursor.getString(0)
Your code seems to be right, I just would check the below things that I mentioned.
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + POSITION + " = " + position;
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int userId;
if (cursor.moveToFirst())
{
userId = cursor.getInt(0);
}
cursor.close();
return userId;
This is a sample code hope you can get a help from this
private void displayListView(String getter){
//get the customer data from the db and feed them to cursor and load the data to lest
Cursor cursor = dbHelper.fetchallcustomercompany(getter);
String[] columns = new String[] {
//get the needed columns of the db and feed them in to string array
DBCreater.Key_customer_Shop
};
int[] to = new int[]{
//get the textboxs in xml layout,which going to display the values in to integer array
R.id.tv_demo_search_text_Isuru
};
//address the xml list view to java
final ListView listView = (ListView)findViewById(R.id.lv_searchcustomer_cuzlist_Isuru);
// feed the context,displaying layout,data of db, data source of the data and distination of the data
if(cursor.getCount()==0){
Toast.makeText(getApplicationContext(), " No matching data", Toast.LENGTH_SHORT).show();
}
else{
dataAdapter = new SimpleCursorAdapter(this, R.layout.demo_search, cursor, columns, to,0);
//load the data to list view
listView.setAdapter(dataAdapter);
//what happen on when user click on the item of the list view
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor =(Cursor)listView.getItemAtPosition(arg2);
//get the value of the customer name from the clicked listitem
String name=cursor.getString(cursor.getColumnIndexOrThrow("customer_shop"));
}
});
}
}
Try this:
public int getItemIdByPosition(int position) {
int itemID = 0;
Cursor localCursor = database.rawQuery("select * from " + TABLE_NAME,
null);
int i = localCursor.getColumnIndex("ID");
if (localCursor.moveToFirst()) {
do {
itemID = Integer.parseInt(localCursor.getString(i));
} while (localCursor.moveToPosition(position));
}
localCursor.close();
return itemID;
}

Delete SQLite row with RecyclerView

Is there a way to delete a row of data in SQLite with RecyclerView? Before when I used a ListView I just set and onClickListener and did :
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
Then passed the id onto my database like so: databaseAdapter.deleteScore(id)
but now since it is all handled in the RecyclerViewAdapter class can you still get the row id and delete it?
Figured it out. What I did was in the RecyclerView's onLongClick(final View view) I created an instance of my sql database and called my deleteScore method as so: sqLiteDBadapter.deleteScore(temp2); <- temp2 is the rowid of the list item in the sql database.
And here is my getRowid and my deleteScore methods in my SQLiteDBadapter class:
getRowid:
public String getRowid(String date) {
mDbHelper = new DatabaseHelper(context);
db = mDbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * from " + DATABASE_TABLE + " WHERE date = ?" , new String[] { date });
if (c.moveToFirst()){
long temp;
temp = c.getLong(c.getColumnIndex(KEY_ROWID));
rowID = String.valueOf(temp);
Log.i("----_ROW ID = ", rowID);
}else if (!c.moveToFirst())
Log.i("CURSOR ERROR", " CURSOR INDEX MOST LIKELY 0");
else
c.moveToFirst();
return rowID;
}
deleteScore:
public boolean deleteScore(long rowId) {
return db.delete(DATABASE_TABLE,KEY_ROWID + "= ?", new String[] { rowID}) > 0;
}

Get selected item name - Android ListView

I have ListView which have items from a database.
My adapter is this:
Cursor cur = myDb.getCategories();
// Closing the cursor
// DEPRECATED!!
startManagingCursor(cur);
// Set up mapping from cursor to view fields
String[] fromFieldNames = new String[] { DBAdapter.KEY_ITEM_CAT };
int[] toViewIDs = new int[] { R.id.tvItemCat };
// Create adapter to map columns of DB to elements on UI
myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.category_layout, // Raw layout template
cur, // Cursor (set of DB records)
fromFieldNames, // DB column names
toViewIDs // views ID to putt in list view
);
// Set the adapter for list view
LVCat.setAdapter(myCursorAdapter);
getCategories():
Cursor c = db.rawQuery("SELECT DISTINCT " + KEY_ITEM_CAT + " as " + KEY_ITEM_ID
+ ", " + KEY_ITEM_CAT + " FROM " + ITEMS_TABLE_NAME, null);
if (c != null) {
c.moveToFirst();
}
return c;
I want when i click on some item I should get item name.
I've search and i found this code:
public void onCatClick(){
LVCat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
String category = LVCat.getItemAtPosition(position).toString();
// String category = parent.getItemAtPosition(position).toString(); --> This also I've tried, but the same result
System.out.println("Cat: " + category);
}
});
}
For other people this works. But I don't get the item name i get something like this:
System.out(23858): Cat: android.database.sqlite.SQLiteCursor#4197f3a0
So how can I get the selected item name?
Use parent.getItemAtPosition(position).toString() in your onItemClickListener to get item.
or use it
TextView tv = (TextView) v.findViewById(R.id.tvItemCat);
String value = tv.getText().toString();

Android get single row from database based on listview id

//function which is in my DatabaseHelper class which extends SQLiteOpenHelper
public String getCoordinatesLatitude(int id) {
String rowLat = "";
SQLiteDatabase db = this.getReadableDatabase();
String latQuery = "SELECT " + KEY_LATITUDE + "FROM " + TABLE_COORDINATES + "WHERE " + KEY_ID + "=" + id;
Cursor cursorr = db.rawQuery(latQuery,null);
if (cursorr != null){
cursorr.moveToPosition(id);
rowLat = cursorr.getString(cursorr.getColumnIndex(KEY_LATITUDE));
}
// return coordinates
return rowLat;
}
//function in my main activity
public void onListItemClick(ListView l, View v, int position, long id) {
selectedFromList = (String) (l.getItemAtPosition(position));
selectedItem = (int) l.getItemIdAtPosition(position);
String rowLat = helper.getCoordinatesLatitude(selectedItem);
Toast.makeText(getApplicationContext(), rowLat, Toast.LENGTH_SHORT).show();
}
I have a listview which contains locations. Each location contains latitude,longitude and a date. What i basically want is to click on a listview item, and retrieve the items latitude value from my database, based on its listview ID. I setup the getCoordinatesLatitude() function but i dont know if my code is correct, because when i click on a listview item i get force close and logcat shows nullPointerException. How can i make this work? Thanks
What my listview looks like
UPDATE!!!!
I managed to get rid of nullPointerException error, and changed my code to this
public String getLatitudeFromId(long id) {
String rowLat = "not found";
SQLiteDatabase db = this.getReadableDatabase();
//String latQuery = "SELECT " + KEY_LATITUDE + " FROM " + TABLE_COORDINATES + " WHERE " + KEY_ID + "=" + id;
//Cursor cursor = db.rawQuery(latQuery,null);
Cursor cursor = db.query(TABLE_COORDINATES, new String[] { "latitude" },"id="+id, null, null, null,null);
if (cursor.moveToFirst()){
cursor.moveToPosition((int) id);
rowLat = cursor.getString(cursor.getColumnIndex("latitude"));
}
cursor.close();
db.close();
// return coordinates
return rowLat;
}
and
public void onListItemClick(ListView l, View v, int position, long id) {
DatabaseHelper helper = new DatabaseHelper(this);
selectedFromList = (String) (l.getItemAtPosition(position));
selectedItem = l.getItemIdAtPosition(position);
String rowLat = helper.getLatitudeFromId(selectedItem);
Toast.makeText(getApplicationContext(), rowLat, Toast.LENGTH_SHORT).show();
}
But now, when i click on listview item, the toast is not found, so it stops in the if (cursor.moveToFirst()) statement because the cursor is empty. How can the cursor be empty when my listview is full of items? :P
UPDATE2
I fixed the problem just by changing my query to this Cursor cursor = db.query(TABLE_COORDINATES, new String[] {KEY_DATE}, null, null, null, null,null); where KEY_DATE is the column name that you want to be shown when u click an item in the listview
If the array which you have assigned to listview adapter is "array" then you can retrieve array.get(position).getLatitude(); (I assume you have use custom adapter)
First your table must have a column set as primary key named _id not id. Then you can pass to getLatitudeFromId the id you get from onItemClick.
Change getLatitudeFromId(long id) to this:
public String getLatitudeFromId(long id) {
String rowLat = "not found";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_COORDINATES, new String[] { "latitude" },"_id=" + id, null, null, null,null);
if (cursor.moveToFirst()){
rowLat = cursor.getString(cursor.getColumnIndex("latitude"));
}
cursor.close();
db.close();
// return coordinates
return rowLat;
}
Change onListItemClick to this:
public void onListItemClick(ListView l, View v, int position, long id) {
DatabaseHelper helper = new DatabaseHelper(this);
// ??? selectedFromList = (String) (l.getItemAtPosition(position));
// ??? selectedItem = l.getItemIdAtPosition(position);
String rowLat = helper.getLatitudeFromId(id);
Toast.makeText(getApplicationContext(), rowLat, Toast.LENGTH_SHORT).show();
}
Note: l.getItemAtPosition(position) returns a view not string neither int
i actually worked my way out. Strangely though, i changed my query to this
Cursor cursor = db.query(TABLE_COORDINATES, new String[] {KEY_DATE}, null, null, null, null,null);
just letting the selection to null and only having the column that i wanted, and it worked! This question can be marked as answered.

Categories

Resources