NullPointer while using Cursor - android

I couldn't find a suitable title for my question. Here is the problem... After syso'ing the statement in getData(), it should print the values in the cursor, cMainTable, using the statement in displayDataForMainTable(). But, it doesn't. There are no exceptions, and errors. I have also kept the output that i get in the LogCat. Can someone help me with, why there is no output after the first print.
try {
pm = new PortfolioManager(this);
cMainTable = pm.getData("mainTable");
if (cMainTable.equals(null)) {
System.out.println("Null is returned");
}
displayDataForMainTable(cMainTable);
}
catch (Exception e) {
System.out.println("problem at Oncreate Method");
}
getData() method:
public Cursor getData(String string) {
System.out.println("Getting Data for Table " + string);
c = sqlDB.rawQuery("select * from " + string, null);
return c;
}
displayDataForMainTable() method:
private void displayDataForMainTable(Cursor c2) {
try {
if (c2 != null) {
if (c2.getCount() > 0) {
c2.moveToFirst();
do {
String SNo = c2.getString(c2.getColumnIndex("scriptnumber"));
String SName = c2.getString(c2.getColumnIndex("scriptname"));
int quant = Integer.parseInt(c2.getString(c2.getColumnIndex("totalquantity")));
double avg = Double.parseDouble(c2.getString(c2.getColumnIndex("averageprice")));
double cur = Double.parseDouble(c2.getString(c2.getColumnIndex("currentprice")));
double log = Double.parseDouble(c2.getString(c2.getColumnIndex("lossorgain")));
System.out.println("Inserted Values are ::: " + SNo
+ " " + SName + " " + String.valueOf(quant)
+ " " + String.valueOf(avg) + " "
+ String.valueOf(cur) + " "
+ String.valueOf(log));
} while (c2.moveToNext());
}
}
else {
System.out.println("Cursor c2 is Empty");
}
} catch (Exception e) {
System.out.println("Exception in displayDataForMainTable");
}
}
output
01-18 11:02:27.523: D/dalvikvm(468): GC_EXTERNAL_ALLOC freed 47K, 53% free 2567K/5379K, external 2090K/2137K, paused 45ms
01-18 11:02:33.983: I/System.out(468): Getting Data for Table mainTable
01-18 11:02:36.584: W/KeyCharacterMap(468): No keyboard for id 0
01-18 11:02:36.584: W/KeyCharacterMap(468): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
Edit 1 :::
I have modified the getData() as suggested by Nasser, but the output remains the same..
public Cursor getData(String string) {
System.out.println("Getting Data for Table "+string);
String table = string;
sqlDB = getReadableDatabase();
c = sqlDB.query(table, null, null, null, null, null, null);
//c = sqlDB.rawQuery("select * from "+string, null);
return c;
}
As I read, passing null to the columns(2nd argument) will return all the rows. If this is correct, then the result is the same.

i think u should not return cursor from db instead of that create a setterGetter class set data in its object and return array of that object..
here's my code for same.. try..
also put logs there so u'll get idea about what is going on..
public ArrayList<ContactSetterGetter> getAllNumbers() {
ArrayList<ContactSetterGetter> setterList = new ArrayList<ContactSetterGetter>();
db = getWritableDatabase();
Cursor c = db.query(C_TABLE_NAME, new String[] {"contact_number"},null, null, null, null, null);
if (c.getCount() != 0) {
c.moveToFirst();
do {
ContactSetterGetter setter = new ContactSetterGetter();
setter.setContactNumber(c.getString(0));
setterList.add(setter);
} while (c.moveToNext());
}else{
c.close();
db.close();
return setterList;
}
c.close();
db.close();
return setterList;
}

It seems that Eclipse has shown mercy on me and is displaying the output. Fought for over 4 hours changing code, surfing, finally ended up with no changes in code.
No matter how smart you are as a coder, IDEs always make you feel a novice.

Related

Cursor Exception during Async Task

I am running a background task that goes out and downloads a JSON file, pareses it, then adds it to the contents to a SQLite database.
I am getting a couple of errors when it runs.
Caused by: android.database.CursorWindowAllocationException: Cursor
window allocation of 2048 kb failed. # Open Cursors=728 (# cursors
opened by this proc=728)
E/CursorWindow: Could not allocate CursorWindow
'/data/data/com.mycompany.inventory/databases/dbInventory.sql' of size
2097152 due to error -12.
The JSON has about 1500 items in it.
Here is the method my async task calls:
public void addModelsToDB(JSONObject dict){
String insertQuery = "";
String deleteQuery = "DROP TABLE IF EXISTS 'tblModels'";
String createQuery = "CREATE TABLE 'tblModels' ('modelsID' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,'makeKey' INTEGER, 'modelName' TEXT, 'modelKey' INTEGER)";
Cursor cursor = dbLocals.executeRawQuery(deleteQuery, null);
cursor.moveToFirst();
cursor = dbLocals.executeRawQuery(createQuery, null);
cursor.moveToFirst();
try {
JSONArray dicRecordSet = dict.getJSONArray("Recordset");
JSONObject dicRecords = dicRecordSet.getJSONObject(0);
JSONArray arrRecords = dicRecords.getJSONArray("Record");
for (int i = 0; i < arrRecords.length(); i++) {
JSONObject record = arrRecords.getJSONObject(i);
insertQuery = "INSERT INTO 'tblModels' VALUES(" + null + ", "
+ record.getString("MODMAKlMakeKey") + ", '"
+ record.getString("MODvc50Name").replaceAll("'", "''") + "', "
+ record.getString("MODlModelKey")
+")";
cursor = dbLocals.executeRawQuery(insertQuery, null);
cursor.moveToFirst();
}
} catch (JSONException e) {
e.printStackTrace();
}
cursor.close();
}
My database a manager returns a cursor.
public Cursor executeRawQuery(String query, String[] selectionArgs) {
Cursor cursor = databaseConn.rawQuery(query, selectionArgs);
return cursor;
}
What am I doing wrong?
You can't reuse the cursor variable because it shadows the original one, and therefore you can't close it:
Cursor cursor = dbLocals.executeRawQuery(deleteQuery, null);
then
cursor = dbLocals.executeRawQuery(insertQuery, null);
this second assignment means you can't close the original cursor.
Also, why are you creating the table here?
Edit:
Use it like this:
public void addModelsToDB(JSONObject dict){
String insertQuery = "";
String deleteQuery = "DROP TABLE IF EXISTS 'tblModels'";
String createQuery = "CREATE TABLE 'tblModels' ('modelsID' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,'makeKey' INTEGER, 'modelName' TEXT, 'modelKey' INTEGER)";
Cursor cursor = dbLocals.executeRawQuery(deleteQuery, null);
try {
cursor.moveToFirst();
cursor = dbLocals.executeRawQuery(createQuery, null);
cursor.moveToFirst();
} finally {
cursor.close();
}
try {
JSONArray dicRecordSet = dict.getJSONArray("Recordset");
JSONObject dicRecords = dicRecordSet.getJSONObject(0);
JSONArray arrRecords = dicRecords.getJSONArray("Record");
for (int i = 0; i < arrRecords.length(); i++) {
JSONObject record = arrRecords.getJSONObject(i);
insertQuery = "INSERT INTO 'tblModels' VALUES(" + null + ", "
+ record.getString("MODMAKlMakeKey") + ", '"
+ record.getString("MODvc50Name").replaceAll("'", "''") + "', "
+ record.getString("MODlModelKey")
+")";
cursor = dbLocals.executeRawQuery(insertQuery, null);
try {
cursor.moveToFirst();
} finally {
cursor.close();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You should close cursors after using them. Inside the loop, you are creating a cursor every iteration, without ever closing it. Apparently there is a limit for the number of open cursors and you hit that limit.

how to get sum of values of cursor retrieved values in Android

i have retrieved some values from DB using the query which is given below.
public Cursor getcredittranscation(String date)
{
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date =? AND T.Trans_Type=? ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{date, "credit"});
return cursor;
}
And in main activity i want to show these results as a report. Activity code is as given below.
try{
db.open();
Cursor c = db.getdebittranscation(temp);
if (c.moveToFirst()) {
do {
DisplayDebitDetails(c);
debittotal(c);
} while (c.moveToNext());
}
db.close();
}catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Debit Error ", " "+e.getMessage());
}
private void DisplayDebitDetails(Cursor c) {
String tempdebit = debitView.getText().toString() + " ";
tempdebit= " \t"+tempdebit+ "\n\t" +c.getString(0) + "\t\t\t"
+ c.getString(1) + "\t\t\t" + c.getString(2);
debitView.setText(tempdebit);
Log.e("debit", "Acc No :"+c.getString(0) +"Name :"+c.getString(1)+ "Trans Amnt :"+c.getString(2));
}
}
private void debittotal(Cursor c){
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
Retrieving and viewing all values is ok... But i need the sum of all values in String(2) . which is given in method debittotal(Cursor c). what is the error in that part ?? I am not getting total
you can use getCount() method
int number_of_records = cursor.getCount();
try this and make sure that debitTotalView.getText().toString() is not blank or null
initially that field value must be 0 otherwise it will give you NumberFormatException for invalid int value
replace
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
with
int tmp = Integer.parseInt(debiTotalView.getText().toString().trim());
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp+"");

Android sqlite how to check if a record exists

I would like to check whether a record exists or not.
Here is what I've tried:
MainActivity.class
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Ontext changed " + new String(s.toString()));
strDocumentFrom = s.toString();
if(s.toString().isEmpty()){
} else {
try{
strTransactionDate = dbHelper.getTransactionDateByDocumentNumber(strDocumentFrom);
//strTotalAmount = dbHelper.getTotalAmountByDocumentNumber(strDocumentFrom);
//strVan = dbHelper.getVanByDocumentNumber(strDocumentFrom);
//etTransactionDate.setText(strTransactionDate);
//etTotalAmount.setText(strTotalAmount);
//Log.d("Van", "" + strVan);
//etVan.setText(strVan);
} catch (SQLiteException e) {
e.printStackTrace();
Toast.makeText(ReceivingStocksHeader.this,
"Document number does not exist.", Toast.LENGTH_SHORT).show();
}
}
DBHelper.class
// TODO DISPLAYING RECORDS TO TRANSRCVHEADER
public String getTransactionDateByDocumentNumber(String strDocumentNumber){
String[] columns = new String[]{KEY_TRANSACTIONDATE};
Cursor c = myDataBase.query(TBL_INTRANS,
columns, null,
null, null, null, null, null);
if(c != null){
c.moveToFirst();
String date = c.getString(0);
return date;
} else {
Log.d("Error", "No record exists");
}
return null;
}
But it doesn't get it to the catch block to display the toast.
What am I doing wrong in here?
public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
I hope this is useful to you...
This function returns true if record already exists in db. Otherwise returns false.
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally: You can get an error when searching by String that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40". Those dashes (-) will cause an unrecognized token error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
Raw queries are more vulnerable to SQL Injection. I will suggest using query() method instead.
public boolean Exists(String searchItem) {
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = { searchItem };
String limit = "1";
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Source: here
SELECT EXISTS with LIMIT 1 is much faster.
Query Ex: SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);
Code Ex:
public boolean columnExists(String value) {
String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();
// cursor.getInt(0) is 1 if column with value exists
if (cursor.getInt(0) == 1) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
You can use SELECT EXISTS command and execute it for a cursor using a rawQuery,
from the documentation
The EXISTS operator always evaluates to one of the integer values 0
and 1. If executing the SELECT statement specified as the right-hand
operand of the EXISTS operator would return one or more rows, then the
EXISTS operator evaluates to 1. If executing the SELECT would return
no rows at all, then the EXISTS operator evaluates to 0.
I have tried all methods mentioned in this page, but only below method worked well for me.
Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
showMessage("Error", "Record exist");
}
else
{
// Inserting record
}
One thing the top voted answer did not mention was that you need single quotes, 'like this', around your search value if it is a text value like so:
public boolean checkIfMyTitleExists(String title) {
String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
Cursor cursor = database.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Otherwise, you will get a "SQL(query) error or missing database" error like I did without the single quotes around the title field.
If it is a numeric value, it does not need single quotes.
Refer to this SQL post for more details
SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.
if(cursor.getCount()<=0){
Log.v("tag","if 1 "+cursor.getCount());
return false;
}
Log.v("tag","2 else "+cursor.getCount());
return true;
if you not use cursor.moveToLast();
cursor.getCount() always give same integer (1) or current position of cursor.
Code :
private String[] allPushColumns = { MySQLiteHelper.COLUMN_PUSH_ID,
MySQLiteHelper.COLUMN_PUSH_TITLE, MySQLiteHelper.COLUMN_PUSH_CONTENT, MySQLiteHelper.COLUMN_PUSH_TIME,
MySQLiteHelper.COLUMN_PUSH_TYPE, MySQLiteHelper.COLUMN_PUSH_MSG_ID};
public boolean checkUniqueId(String msg_id){
Cursor cursor = database.query(MySQLiteHelper.TABLE_PUSH,
allPushColumns, MySQLiteHelper.COLUMN_PUSH_MSG_ID + "=?", new String [] { msg_id }, null, null, MySQLiteHelper.COLUMN_PUSH_ID +" DESC");
if(cursor.getCount() <= 0){
return false;
}
return true;
}
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
because of possible data leaks best solution via cursor:
Cursor cursor = null;
try {
cursor = .... some query (raw or not your choice)
return cursor.moveToNext();
} finally {
if (cursor != null) {
cursor.close();
}
}
1) From API KITKAT u can use resources try()
try (cursor = ...some query)
2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'
3) dont use moveToFirst() is used when you need to start iterating from beggining
4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.
Try to use cursor.isNull method.
Example:
song.isFavorite = cursor.isNull(cursor.getColumnIndex("favorite"));
You can use like this:
String Query = "Select * from " + TABLE_NAME + " where " + Cust_id + " = " + cust_no;
Cursor cursorr = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursorr.close();
}
cursor.close();
private boolean checkDataExistOrNot(String columnName, String value) {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM" + TABLE_NAME + " WHERE " + columnName + " = " + value;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false; // return false if value not exists in database
}
cursor.close();
return true; // return true if value exists in database
}
I prefer to do it this way because it's fast and less expensive than other methods:
Cursor cursor = db.rawQuery("SELECT 1 FROM table WHERE condition = 1 LIMIT 1", null);
try {
if (cursor.moveToNext()) {
//Record exists
} else {
//Record doesn't exists
}
} finally {
cursor.close();
}
My version:
public boolean isTitleExists(String title, String type) {
int isExists = 0;
try {
String query = "SELECT EXISTS (SELECT 1 FROM titles WHERE title = ? and type = ?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, title);
statement.setString(2, type);
ResultSet rs = statement.executeQuery();
rs.next();
isExists = rs.getInt(1);
rs.close();
statement.close();
} catch (SQLException e) {
Common.console("isTitleExists error: " + e.getMessage());
}
return isExists == 1;
}

Handling Invalid SQLite Queries in Android

I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.
My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.
So far my method for searching looks like this:
public String search(DataBaseHelper myDB){
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
cursor.moveToFirst();
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
cursor.getString(cursor.getColumnIndex("Room"));
//Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
//msg.show();
cursor.close();
return data;
}
Cursor cursor = NULL ;
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
if(cursor != NULL)
{
try {
if (cursor.moveToNext()) {
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) +
" " + cursor.getString(cursor.getColumnIndex("Room"));
} else {
// Query result was empty, deal with it here.
}
} finally {
// Cursors should be closed
cursor.close();
}
}
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
//print exception
}
Cursor cursor = null;
String data = "";
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
// TODO: handle exception
}

Garabage value in list

i'm populating a list view to view my record, i've the following code...
super.onCreate(savedInstanceState);
setContentView(R.layout.total);
ArrayList<Object> results = new ArrayList<Object>();
// -- SQLiteOpenHelper dbHelper = new DatabaseHelper(this, SAMPLE_DB_NAME, null, 1);
SQLiteDatabase myDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READONLY, null);
try {
/* Create the Database (no Errors if it already exists) */
myDB.execSQL("PRAGMA foreign_keys = ON;");
// -- openOrCreateDatabase(name, mode, factory)
// myDB = dbHelper.getReadableDatabase();
Cursor c = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAME, null, null, null, null, null, null);
Cursor d = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAMES, null, null, null, null, null, null);
/* Check if our result was valid. */
if (c != null && d != null) {
c.moveToFirst(); // it's very important to do this action otherwise your Cursor object did not get work
d.moveToFirst();
char cust_name = (char) c.getColumnIndex("cust_name");
char pro_name = (char) d.getColumnIndex("pro_name");
int pro_price = (int) d.getColumnIndex("pro_price");
/* Check if at least one Result was returned. */
if (c.isFirst() && d.isFirst()) {
int i = 0;
/* Loop through all Results */
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_name + " (" + pro_name + ": " + pro_price + ")");
} while (c.moveToNext()&& d.moveToNext());
}
}
} catch (SQLiteException e) {
} finally {
if (myDB != null)
myDB.close();
}
// -- android.R.layout.simple_list_item_1 is object which belong to ListActivity itself
// -- you only need to add list object in your main layout file
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, results));
}
total.xml
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="380dp"
android:cacheColorHint="#00000000" >
</ListView>
the data is successfully inserted to sqlite (confirmed from adb shell)...it gives me garbage value...can any one please figure out the issue....Thanks in advance
That is not garbage values references(memory) addresses, use below code it will work.
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_nameColumnIndex + " (" + pro_nameColumnIndex + ": " + pro_priceColumnIndex + ")");
} while (c.moveToNext()&& d.moveToNext());
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, (String[]) results.toArray(new String[0])));
Try changing the way you read your cursors. Something like that might be better:
//Get the indexes
int cust_name = cursor.getColumnIndex("cust_name");
int pro_name = cursor.getColumnIndex("pro_name");
int pro_price = cursor.getColumnIndex("pro_price");
try {
if(cursor.moveToFirst()){
while (!cursor.isAfterLast()) {
//Get the data
String cust_nameColumnIndex = cursor.getString(cust_name);
String pro_nameColumnIndex = cursor.getString(pro_name);
int pro_priceColumnIndex = cursor.getInt(pro_price);
//Move to next cursor item
cursor.moveToNext();
}
}
else {
Log.i(TAG, "Empty cursor");
//Do whatever
}
} catch (Exception e) {
Log.i(TAG, "Exception while reading cursor: " + e.getMessage());
//Do whatever
}
finally {
cursor.close();
}

Categories

Resources