delete zero index of listview which populated from database Android - 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.

Related

Store SQLite query result in a String array

How can I save a query result in a String array?
The query is simple, it's got only one column i.e.:
SELECT NAME FROM MYTABLE
What I want is to store the ids in a String array so I can show them as clickable items in a ListView
Try this
String selectQuery = "SELECT * FROM table";
try {
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<String> ids = new ArrayList<>();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(KEY_ID));
ids.add(id);
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
Assuming you've already executed your query against a SQLiteDatabase object, and received a Cursor in return, you can iterate through the cursor and save the value of each row to a String[] array like so:
String[] names;
if (cursor.moveToFirst()) {
names = new String[cursor.getCount()];
int colIndex = cursor.getColumnIndex("NAME");
do {
names[cursor.getPosition()] = cursor.getString(colIndex);
} while (cursor.moveToNext());
}
Keep in mind that names will be null if no rows are returned, so make sure you do a null check.
create following method in SQLiteOpenHelper class
public List<String> getAllNames() {
List<String> retData = new ArrayList<String>();
String selectQuery = "SELECT NAME FROM MYTABLE";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
retData.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return retData;
}
then assign this returned list to adapter
The issue with listing id's is that they tend to be meaningless to an end user. Really you want to display user meaningful data, e.g. a name, but to then be able to access the respective id to then efficiently act on a selection from the list presented to a user.
Using an ArrayList is frequently the cause of much frustration, as the list shows what is required but it's then found to be of little use when attempting to use the list beyond displaying data e.g. selecting an item to then do something such as delete or update (if the value is unique within the database it can be used).
As such an ArrayList<your_object> rather then an ArrayList<String> is generally more viable as the source of the List; a Cursor Adapter can also be used as data from the underlying row is easily obtained.
However, there is an issue, unless a Custom Array Adapter is utilised, when using an ArrayList in that the ArrayAdapter class uses the toString method of the object to retrieve the data that is displayed. The simple fix is to provide a suitable toString method in the object, if you don't you will get something long the lines of “SomeType#2f92e0f4”.
Example showing all 3
In the following working example :-
the database (mydb) has 1 table named mytable which has two columns _id (Note must be _id for a CursorAdapter)
There are 3 methods to get the 3 types of list (named accordingly) :-
getAllAsStringArrayList (gets ArrayList)
getAllAsMyTableObjectArrayList (gets ArrayList). Note uses the MyTableObject class (see note in class re overriding the default toString method)
getAllAsCursor
The App, when run, will have 3 lists, the left based upon the first ArrayList, the middle based upon the ArrayList and the last based upon the Cursor.
Clicking an item in any of the lists displays the respective name along with attempts to get the id.
The ArrayList, Left List, fails in this aspect as it can only get the position (i.e. the 4th parameter passed to the listener is the same value as the position).
The ArrayList, middle List, when getting the id from the object (which is retrieved via the getItem(position) method of the Adapter) successfully retrieves the correct id, the 4th parameter is the same as the position, and should not be used.
The Cursor, Right List, retrieves the correct id both via the Cursor and the 4th parameter.
The Code
MyTableObject.java :-
public class MyTableObject {
private long id;
private String name;
public MyTableObject(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
NOTE toString method returns just the name
*/
#Override
public String toString() {
return name;
}
}
DatabaseHelper.java :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_MYTABLE = "mytable";
public static final String COl_MYTABLE_ID = BaseColumns._ID; //<<<< use standard android id column name
public static final String COL_MYTABLE_NAME = "_name";
private static final String mytable_crtsql =
"CREATE TABLE IF NOT EXISTS " + TB_MYTABLE +
"(" +
COl_MYTABLE_ID + " INTEGER PRIMARY KEY, " +
COL_MYTABLE_NAME + " TEXT " +
")";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mytable_crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addRow(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_MYTABLE_NAME,name);
return mDB.insert(TB_MYTABLE,null,cv);
}
public ArrayList<String> getAllAsStringArrayList() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME)));
}
csr.close();
return rv;
}
public ArrayList<MyTableObject> getAllAsMyTableObjectArrayList() {
ArrayList<MyTableObject> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new MyTableObject(
csr.getLong(csr.getColumnIndex(COl_MYTABLE_ID)),
csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME))
)
);
}
csr.close();
return rv;
}
public Cursor getAllAsCursor() {
return mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
}
}

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

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.

Android Listview onListItemClick get Sqlite Id

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

Categories

Resources