CursorOutofBoundsException Index -1 requested with size of 0 - android

I have a database called updateparty from which i have to create a array list of type hashmap string.When i try to retrieve data from db,the cursor does not move to next record.
Here is the code for db insertion.
for (int i = 0; i < poslist.size(); i++) {
SQLiteDatabase db7 = db.getWritableDatabase();
ContentValues values5= new ContentValues();
values5.put(DBManager.TableInfo.KEYID, ID1);
values5.put(DBManager.TableInfo.DOCU, document);
values5.put(DBManager.TableInfo.ATTEND,attendancelist.get(i));
values5.put(DBManager.TableInfo.EMAIL, emaillist.get(i));
values5.put(DBManager.TableInfo.PARTY,partytypelist.get(i) );
values5.put(DBManager.TableInfo.BIO,biometriclist.get(i));
values5.put(DBManager.TableInfo.KEY_LOGIN_USER,username2);
String condition5 = DBManager.TableInfo.DOCU + " =?";
Cursor cursor5 = db7.query(DBManager.TableInfo.UPDATEPARTY, null, condition5, new String[]{DBManager.TableInfo.ATTEND}, null, null, null);
long status5 = db7.insert(DBManager.TableInfo.UPDATEPARTY, null, values5);
System.out.println( "Parties insert : " + status5);
cursor5.close();
db7.close();
}
Code to create arraylist from above db:
public ArrayList<HashMap<String, String>>getPartypost(DBOperation db) {
ArrayList<HashMap<String, String>> listParties11 = new ArrayList<HashMap<String, String>>();
try {
String query = "select * from " + DBManager.TableInfo.UPDATEPARTY + " where " + DBManager.TableInfo.KEY_LOGIN_USER + " = '" + GenericMethods.email + "'";
System.out.println("query:"+query);
SQLiteDatabase sqlite1 = db.getWritableDatabase();
Cursor c = sqlite1.rawQuery(query, null);
while(c.moveToNext()) {
HashMap<String, String> selectiondetails10 = new HashMap<String, String>();
System.out.println("value:"+c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("document_id", c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("att_id", c.getString(c.getColumnIndex(DBManager.TableInfo.ATTEND)));
selectiondetails10.put("email", c.getString(c.getColumnIndex(DBManager.TableInfo.EMAIL)));
selectiondetails10.put("party_type", c.getString(c.getColumnIndex(DBManager.TableInfo.PARTY)));
selectiondetails10.put("biometric", c.getString(c.getColumnIndex(DBManager.TableInfo.BIO)));
selectiondetails10.put("exec_email", c.getString(c.getColumnIndex(DBManager.TableInfo.KEY_LOGIN_USER)));
listParties11.add(selectiondetails10);
}
closeCursor(c);
//}
// }
System.out.println("list size:"+listParties11.size());
} catch (Exception e) {
// TODO: handle exception.
e.printStackTrace();
}
db.close();
return listParties11;
}
This is the error message:
What i need is to create a arraylist from this db

change your insertion code to this:
SQLiteDatabase db7 = db.getWritableDatabase();
ContentValues values5= new ContentValues();
for (int i = 0; i < poslist.size(); i++) {
values5.put(DBManager.TableInfo.KEYID, ID1);
values5.put(DBManager.TableInfo.DOCU, document);
values5.put(DBManager.TableInfo.ATTEND,attendancelist.get(i));
values5.put(DBManager.TableInfo.EMAIL, emaillist.get(i));
values5.put(DBManager.TableInfo.PARTY,partytypelist.get(i) );
values5.put(DBManager.TableInfo.BIO,biometriclist.get(i));
values5.put(DBManager.TableInfo.KEY_LOGIN_USER,username2);
String condition5 = DBManager.TableInfo.DOCU + " =?";
Cursor cursor5 = db7.query(DBManager.TableInfo.UPDATEPARTY, null, condition5, new String[]{DBManager.TableInfo.ATTEND}, null, null, null);
long status5 = db7.insert(DBManager.TableInfo.UPDATEPARTY, null, values5);
System.out.println( "Parties insert : " + status5);
cursor5.close();
db7.close();
}

Use following code , while loop should be like this:
while(!c.isAfterLast())
public ArrayList<HashMap<String, String>>getPartypost(DBOperation db) {
ArrayList<HashMap<String, String>> listParties11 = new ArrayList<HashMap<String, String>>();
try {
String query = "select * from " + DBManager.TableInfo.UPDATEPARTY + " where " + DBManager.TableInfo.KEY_LOGIN_USER + " = '" + GenericMethods.email + "'";
System.out.println("query:"+query);
SQLiteDatabase sqlite1 = db.getWritableDatabase();
Cursor c = sqlite1.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()) {
HashMap<String, String> selectiondetails10 = new HashMap<String, String>();
System.out.println("value:"+c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("document_id", c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("att_id", c.getString(c.getColumnIndex(DBManager.TableInfo.ATTEND)));
selectiondetails10.put("email", c.getString(c.getColumnIndex(DBManager.TableInfo.EMAIL)));
selectiondetails10.put("party_type", c.getString(c.getColumnIndex(DBManager.TableInfo.PARTY)));
selectiondetails10.put("biometric", c.getString(c.getColumnIndex(DBManager.TableInfo.BIO)));
selectiondetails10.put("exec_email", c.getString(c.getColumnIndex(DBManager.TableInfo.KEY_LOGIN_USER)));
listParties11.add(selectiondetails10);
c.moveToNext();
}
closeCursor(c);
//}
// }
System.out.println("list size:"+listParties11.size());
} catch (Exception e) {
// TODO: handle exception.
e.printStackTrace();
}
db.close();
return listParties11;
}

Related

Want to create,update and retrieve data from SqLite

For Create table :
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID + " REAL NOT NULL" +"," + TOTAL_DISPLACEMENT_DISTANCE + " REAL NOT NULL" + "" + ");");
}
for Update table, want to save only displacement so i update every time because i want to override the data.
public void insertTotalDisplacement(String userID, Double displacement) {
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, userID); //User phone No used as a USER ID
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues, NewDatabaseForInRideData.USER_ID+" = "+userID, new String [] {});
} catch (Exception e) {
e.printStackTrace();
}
}
For Retrieving data, I used several ways to do this but data not save in database and not retrieved from database.
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
// cursor = database.rawQuery(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
//choice = String.valueOf(cursor.getDouble(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE)));
Cursor cur=database.rawQuery("SELECT "+NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE+" where "+NewDatabaseForInRideData.USER_ID+" = " +1+ " from"+NewDatabaseForInRideData.IN_RIDE_DATA,new String [] {});
//Cursor cur=database.rawQuery("SELECT * from IN_RIDE_DATA",new String [] {});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
The issue is in getTotalDisplacementDistance method, you are using two cursor variables, one has query result and other is null, and you are processing the one with null value.
Update it accordingly,
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
cursor = database.rawQuery("SELECT " + NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE + " from IN_RIDE_DATA where " + NewDatabaseForInRideData.USER_ID + " = ?", new String[] {"1"});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
You can try this
String selectQuery = "SELECT * FROM " + IN_RIDE_DATA;
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.USER_ID))));
contact.setName(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE))));
// Adding data to your list
list.add(contact);
} while (cursor.moveToNext());
db.setTransactionSuccessful();
}
db.endTransaction();
Edit
Use you model class for setting data
I change these things
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
//database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID +"," + TOTAL_DISPLACEMENT_DISTANCE + "" + ");");
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT"+");");
}
For Deleting Table
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
For Inserting
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For retrieving the values:
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

Sent messages are shown duplicated in my List View

private class getItemLists extends AsyncTask<Void, String, String> {
private Context mContext;
public getItemLists(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ld.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Intent i = new Intent("notify.intent.MAIN");
// mContext.sendBroadcast(i);
}
#Override
protected String doInBackground(Void... params) {
try {
Chatdb db = new Chatdb(mContext);
String[] smsid = db.getAllinboxsmsid();
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body",
"date", "read" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = mContext.getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
boolean exists = false;
if (c.moveToLast()) {
do {
exists = false;
publishProgress((c.getCount() - c.getPosition() + ";" + c
.getCount()));
for (int x = 0; x < smsid.length; x++) {
if (smsid[x].equals(c.getString(0))) {
exists = true;
}
}
if (!exists) {
if (c.getString(4).equals("0")) {
smsRead = "1";
} else {
smsRead = "0";
}
db.addMsgWithTime(c.getString(1), c.getString(2),
"1", "0", "L", c.getString(0),
c.getString(3), smsRead);
publishProgress((c.getCount() - c.getPosition()
+ ";" + c.getCount()));
// Intent in = new
// Intent("SmsMessage.intent.MAIN").putExtra(
// "get_msg", c.getString(1));
//
// // You can place your check conditions here(on
// the SMS or the
// // sender)
// // and then send another broadcast
// SuperMain.this.sendBroadcast(in);
}
} while (c.moveToPrevious());
}
// c.close();
//
String[] SentSmsId = db.getAllsentsmsid();
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqColsSent = new String[] { "_id", "address", "body",
"date", "read" };
// Get Content Resolver object, which will deal with Content
// Provider
// Fetch Inbox SMS Message from Built-in Content Provider
c = cr.query(sentURI, reqColsSent, null, null, null);
if (c.moveToLast()) {
do {
exists = false;
publishProgress((c.getCount() - c.getPosition() + ";" + c
.getCount()));
for (int x = 0; x < SentSmsId.length; x++) {
if (SentSmsId[x].equals(c.getString(0))) {
exists = true;
}
}
if (!exists) {
db.addMsgWithTime(c.getString(1), c.getString(2),
"0", "0", "S", c.getString(0),
c.getString(3), "1");
// db.close();
publishProgress((c.getCount() - c.getPosition()
+ ";" + c.getCount()));
}
} while (c.moveToPrevious());
}
c.close();
db.close();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
return "done";
}
#Override
protected void onPostExecute(String done) {
super.onPostExecute(done);
// Toast.makeText(mContext, "Messages have synced successfully",
// 3).show();
ld.setVisibility(View.INVISIBLE);
}
}
This is my Loading procedure of Inbox and Sent messages and showing at mu list view.
here ld is my loader... showing when data is loading
public String[] getAllsentsmsid() {
String selectQuery = "SELECT " + KEY_SMSID + " FROM " + TABLE_THREAD
+ " WHERE " + KEY_SMSID + "<>'0' AND " + KEY_ORIGIN + "='0'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] allid = new String[cursor.getCount()];
int x = 0;
if (cursor.moveToFirst()) {
do {
allid[x] = cursor.getString(0);
x++;
} while (cursor.moveToNext());
}
db.close();
return allid;
}
public String[] getAllinboxsmsid() {
String selectQuery = "SELECT " + KEY_SMSID + " FROM " + TABLE_THREAD
+ " WHERE " + KEY_SMSID + "<>'0' AND " + KEY_ORIGIN + "='1'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] allid = new String[cursor.getCount()];
int x = 0;
if (cursor.moveToFirst()) {
do {
allid[x] = cursor.getString(0);
x++;
} while (cursor.moveToNext());
}
db.close();
return allid;
}
These are my database methods where I am storing messages id and save them in my database.
In my list view making duplicate threads of chatting.

Android - SQLite delete and update data not working well

I created database with few tables, got 1 table called friend. A friend has few expenses, some expenses might share with another friend. Now i am trying to delete a friend, what i am trying to do is when the friend share expenses with another friend, the expense of the friend that shared with another friend will then added to another friend and the expense will not deleted. Then, the expenses that are not shared with another friend is directly deleted and will not added to any friend since the friend has many expenses. Now the problem is when i trying to add the expense to another friend, its not working. And i am not getting any error.
Here is my code : i think the problem occur inside if(sharerList.size()>1)...., since the rest of the code works well.
public void deleteFriend(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM FriendsExpenses WHERE friendId='" + id + "'";
SQLiteDatabase databaseread = this.getReadableDatabase();
Cursor cursor = databaseread.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("expenseId", cursor.getString(0));
wordList.add(map);
} while (cursor.moveToNext());
}
for (int a=0; a<wordList.size();a++){
HashMap<String, String> ValexpenseId = wordList.get(a);
for (Entry<String, String> entry : ValexpenseId.entrySet()) {
String value = entry.getValue();
String selectQuery2 = "SELECT * FROM FriendsExpenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread2 = this.getReadableDatabase();
Cursor cursor2 = databaseread2.rawQuery(selectQuery2, null);
ArrayList<HashMap<String, String>> sharerList = new ArrayList<HashMap<String, String>>();
if (cursor2.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("friendId", cursor2.getString(0));
wordList.add(map);
} while (cursor2.moveToNext());
}
else{};
if (sharerList.size() > 1){
String selectQuery3 = "SELECT expenseTotal FROM expenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread3 = this.getReadableDatabase();
Cursor cursor3 = databaseread3.rawQuery(selectQuery3, null);
String expenseTotal = null;
if (cursor3.moveToFirst()) {
do {
expenseTotal = cursor3.getString(cursor3.getColumnIndex("expenseTotal"));
} while (cursor3.moveToNext());
}
for (int b=0; b<sharerList.size();b++){
HashMap<String, String> ValfriendId = sharerList.get(b);
for (Entry<String, String> entry2 : ValfriendId.entrySet()) {
String value2 = entry2.getValue();
String currentSpend = currentSpending(value2);
double currentSpending = (Double.parseDouble(currentSpend));
double expTotal = (Double.parseDouble(expenseTotal));
double newSpending = currentSpending + ((expTotal/sharerList.size()) /sharerList.size()-1);
updateSpending(value2, newSpending);
}
}
}
else
{
String deleteQuery = "DELETE FROM expenses where expenseId='" + value + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
}
}
String deleteQuery = "DELETE FROM friends where friendId='" + id + "'";
String deleteQuery2 = "DELETE FROM FriendsExpenses where friendId='" + id + "'";
Log.d("query", deleteQuery2);
Log.d("query", deleteQuery);
database.execSQL(deleteQuery2);
database.execSQL(deleteQuery);
}
sharerList is empty because you never add any entries.
There are likely to be other copy/paste errors, such as getString(0) with SELECT *.

Attempted to access a cursor after it has been closed

I'm using the following code to delete an image. It works the first time, but when I try to capture an image and delete it
I get a StaleDataException:
08-07 14:57:24.156: E/AndroidRuntime(789): java.lang.RuntimeException: Unable to
resume activity {com.example.cap_im/com.example.cap_im.MainActivity}:
android.database.StaleDataException: Attempted to access a cursor after it has been closed.
public void deleteImageFromGallery(String captureimageid) {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
getContentResolver().delete(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
BaseColumns._ID + "=?", new String[] { captureimageid });
String[] projection = { MediaStore.Images.ImageColumns.SIZE,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATA, BaseColumns._ID, };
Log.i("InfoLog", "on activityresult Uri u " + u.toString());
try {
if (u != null) {
cursor = managedQuery(u, projection, null, null, null);
}
if ((cursor != null) && (cursor.moveToLast())) {
int i = getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
BaseColumns._ID + "=" + cursor.getString(3), null);
Log.v(TAG, "Number of column deleted : " + i);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Function, managedQuery() is deprecated.
Please use getContentResolver().query().
The parameters is the same.
In your finally block, you close the cursor, but you do not set it to null. Thus, the next time your method is called, cursor.getString(3) fails, since the cursor has been closed.
Workaround: Set cursor to null in your finally block.
Correct solution: Don't use an instance variable for your cursor, use a local variable in your method instead.
I had a similar problem. In my case the code is fine but I used the deprecated method 'managedQuery' rather than the one suggested by Tom Lin
public String getPath(Uri uri) {
if (uri == null) {
return null;
}
String result = null;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
// deprecated:
// Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int columnIndex = 0;
try {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(columnIndex);
} catch (IllegalArgumentException e) {
Log.e("While getting path for file", e);
} finally {
try {
if (!cursor.isClosed()) {
cursor.close();
}
cursor = null;
} catch (Exception e) {
Log.e("While closing cursor", e);
}
}
}
return result;
}
If I use the deprecated method it still works if I omit the finally. It is also explicitly stated in the doc that one should not close the cursor when using this method
Definitely work this code,Use getContentResolver().query() instead of managedQuery(). Because managedQuery() is deprecated. its work for me Perfect.
Also don't use managedQuery() it has been deprecated.
Remove this:
protected SQLiteDatabase database;
and make it local
Basically 2 method are executing concurrently and one method called database.close() and 2nd method is still accessing data so the Exception
use this:
public class db {
DataBaseHelper dbHelper;
Context mContext;
public db(Context context) {
this.mContext = context;
}
public db open() throws SQLException {
dbHelper = new DataBaseHelper(mContext);
return this;
}
public void close() {
dbHelper.close();
}
public void insertdb( int id,String ph_num, String call_type, String calldate, String call_duration, String upload_status) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DataBaseHelper.id,id);
values.put(DataBaseHelper.phone_number, ph_num);
values.put(DataBaseHelper.call_type, call_type);
values.put(DataBaseHelper.call_date, calldate);
values.put(DataBaseHelper.call_duration, call_duration);
values.put(DataBaseHelper.upload_status, upload_status);
database.insert(DataBaseHelper.table_name, null, values);
database.close();
// Log.d("Database helper", "values inserted");
}
public ArrayList<HashMap<String, String>> getAllUsers() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM call_logtable";
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", cursor.getString(0));
map.put("phone_number", cursor.getString(1));
map.put("call_type", cursor.getString(2));
map.put("call_date", cursor.getString(3));
map.put("call_duration", cursor.getString(4));
wordList.add(map);
} while (cursor.moveToNext());
}
cursor.close(); // just added
database.close();
return wordList;
}
/**
* Compose JSON out of SQLite records
* #return
*/
public String composeJSONfromSQLite(){
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM call_logtable where upload_status = '"+"no"+"'";
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", cursor.getString(0));
map.put("phone_number", cursor.getString(1));
map.put("call_type", cursor.getString(2));
map.put("call_date", cursor.getString(3));
map.put("call_duration", cursor.getString(4));
wordList.add(map);
} while (cursor.moveToNext());
}
cursor.close(); // just added
database.close();
Gson gson = new GsonBuilder().create();
//Use GSON to serialize Array List to JSON
return gson.toJson(wordList);
}
public int dbSyncCount(){
int count = 0;
String selectQuery = "SELECT * FROM call_logtable where upload_status = '"+"no"+"'";
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
count = cursor.getCount();
cursor.close(); // just added
database.close();
return count;
}
public void updateSyncStatus(String id, String status){
SQLiteDatabase database = dbHelper.getWritableDatabase();
String updateQuery = "Update call_logtable set upload_status = '"+ status +"' where id="+"'"+ id +"'";
Log.d("query", updateQuery);
database.execSQL(updateQuery);
database.close();
}
public Cursor getinformation()
{
SQLiteDatabase database = dbHelper.getReadableDatabase();
String[] columns={DataBaseHelper.phone_number,DataBaseHelper.call_type,DataBaseHelper.call_date,DataBaseHelper.call_duration,DataBaseHelper.upload_status};
return database.query(DataBaseHelper.table_name,columns,null,null,null,null,null);
}
public void delete()
{
SQLiteDatabase database = dbHelper.getWritableDatabase();
// String[] columns={DataBaseHelper.phone_number,DataBaseHelper.call_type,DataBaseHelper.call_date,DataBaseHelper.call_duration};
database.delete(DataBaseHelper.table_name, null, null);
}
StringBuffer readSpecificfrom_db(String type)
{
String ph_number=null;
String call_type=null;
String call_date=null;
String call_duration=null;
String upload_status=null;
StringBuffer sb = new StringBuffer();
//sb.append("Call Log :");
Cursor cursor_object=getinformation();
cursor_object.moveToFirst();
do {
if((cursor_object.getString(1)).equals(type)) {
ph_number = cursor_object.getString(0);
call_type = cursor_object.getString(1);
call_date = cursor_object.getString(2);
call_duration = cursor_object.getString(3);
if(type=="Missed") {
sb.append("\nPhone Number:--- " + ph_number +
" \nCall Type:--- " + call_type +
" \nCall Date:--- " + call_date
// + " \nCall duration in sec :--- " + call_duration
);
sb.append("\n----------------------------------");
}
else
{
sb.append("\nPhone Number:--- " + ph_number +
" \nCall Type:--- " + call_type +
" \nCall Date:--- " + call_date
+ " \nCall duration in sec :--- " + call_duration);
sb.append("\n----------------------------------");
}
}
}while(cursor_object.moveToNext());
cursor_object.close(); // just added
return sb;
}
StringBuffer readfrom_db()
{
String ph_number=null;
String call_type=null;
String call_date=null;
String call_duration=null;
String upload_status;
// int id=0;
StringBuffer sb = new StringBuffer();
// sb.append("Call Log :");
Cursor cursor_object=getinformation();
cursor_object.moveToFirst();
do {
ph_number=cursor_object.getString(0);
call_type=cursor_object.getString(1);
call_date=cursor_object.getString(2);
call_duration=cursor_object.getString(3);
sb.append("\nPhone Number:--- " + ph_number +
" \nCall Type:--- " + call_type +
" \nCall Date:--- " + call_date
+ " \nCall duration in sec :--- " + call_duration);
sb.append("\n----------------------------------");
} while(cursor_object.moveToNext());
cursor_object.close(); // just added
return sb;
}
}

Access the data from database and put them into String[]

I built a table in the database, and now I want to access the all of the values in a certain column. Finally, I want to put the data into byte[].
Part of my code:
db.execSQL("create table thing(id integer primary key" +
" autoincrement, name varchar(20))");
List<Integer> all = new ArrayList<Integer>();
String sql = " SELECT id from " + DB_NAME;
Cursor result = this.db.rawQuery(sql, null);
for (result.moveToFirst(); result.isAfterLast(); result.moveToNext()) {
all.add(result.getInt(0));
}
String[] fstr = (String[]) all.toArray();
for (String bstr : fstr) {
byte[] bbs = bstr.getBytes();
}
Use this code
String[] fstr = new String[result.getCount()] ;
do {
int posi = result.getPosition();
fstr[posi] =result.getString(0);
}while (result.moveToNext());
try this
Cursor c=this.db.rawQuery(sql, null);
if(c.getCount()>0)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
String str=c.getInt(0));// or c.getString();
}
}
else
{
Log.d(" Null value in cursor ", " null ");
}
c.close();
dbhelper.close();

Categories

Resources