Android get single row from database based on listview id - android

//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.

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

How to get row count in sqlite using Android?

I am creating task manager. I have tasklist and I want when I click on particular tasklist name if it empty then it goes on Add Task activity but if it has 2 or 3 tasks then it shows me those tasks into it in list form.
I am trying to get count in list. my database query is like:
public Cursor getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
if(cursor!=null && cursor.getCount()!=0)
cursor.moveToNext();
return cursor;
}
In My activity:
list_tasklistname.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
Cursor c = db.getTaskCount(id);
System.out.println(c.getCount());
if(c.getCount()>0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
task = adapter.getItem(position);
int taskList_id = task.getTaskListId();
taskListID.putExtra("TaskList_ID", taskList_id);
startActivity(taskListID);
}
else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
});
db.close();
}
but when I am clicking on tasklist name it is returning 1, bot number of tasks into it.
Using DatabaseUtils.queryNumEntries():
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
Use android.database.DatabaseUtils to get number of count.
public long getTaskCount(long tasklist_Id) {
return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}
It is easy utility that has multiple wrapper methods to achieve database operations.
c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.
public int getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery(
"SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) }
);
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
}
db.close();
return count;
}
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
Change your getTaskCount Method to this:
public int getTaskCount(long tasklist_id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
cursor.moveToFirst();
int count= cursor.getInt(0);
cursor.close();
return count;
}
Then, update the click handler accordingly:
public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
// Get task list id
int tasklistid = adapter.getItem(position).getTaskListId();
if(db.getTaskCount(tasklistid) > 0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
taskListID.putExtra("TaskList_ID", tasklistid);
startActivity(taskListID);
} else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
In order to query a table for the number of rows in that table, you want your query to be as efficient as possible. Reference.
Use something like this:
/**
* Query the Number of Entries in a Sqlite Table
* */
public long QueryNumEntries()
{
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "table_name");
}
Do you see what the DatabaseUtils.queryNumEntries() does? It's awful!
I use this.
public int getRowNumberByArgs(Object... args) {
String where = compileWhere(args);
String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
Cursor c = getWriteableDatabase().rawQuery(raw, null);
try {
return (c.moveToFirst()) ? c.getInt(0) : 0;
} finally {
c.close();
}
}
Sooo simple to get row count:
cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
looking at the sources of DatabaseUtils we can see that queryNumEntries uses a select count(*)... query.
public static long queryNumEntries(SQLiteDatabase db, String table, String selection,
String[] selectionArgs) {
String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : "";
return longForQuery(db, "select count(*) from " + table + s,
selectionArgs);
}
Once you get the cursor you can do
Cursor.getCount()

Categories

Resources