App Crashes When Reading Contacts - java

I've got a crash while trying to read the contacts of the user, I thought because it's because of the Emulator, but I want to triple check, as I don't have an android based phone. The Logcat gives an error that, it can't read the row "id" did I incorrectly name that string?
Lastly, how would I implement a dialogue box, to see if the user wants the app to read the contacts?
Thanks so much:)
Code:
private void checkandImportContacts() {
// TODO Auto-generated method stub
SharedPreferences sp = getSharedPreferences(PREFS_CHECK, 0);
String checkfirstime = sp.getString("key3", null);
if(checkfirstime !=null && equals("sdhdasudafdsugdiasgdas38ey98d1diass")) {
finish();
} else {
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Toast.makeText(getApplicationContext(), displayName, Toast.LENGTH_LONG).show();
}
}
}
private Cursor getContacts() {
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ‘" + ("1") + "’";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
LogCat:
04-23 16:49:48.288: E/AndroidRuntime(437): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: android.database.sqlite.SQLiteException: no such column: ‘1’: , while compiling: SELECT _id, display_name FROM view_contacts_restricted WHERE (in_visible_group = ‘1’) ORDER BY display_name COLLATE LOCALIZED ASC
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.os.Looper.loop(Looper.java:123)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-23 16:49:48.288: E/AndroidRuntime(437): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:49:48.288: E/AndroidRuntime(437): at java.lang.reflect.Method.invoke(Method.java:521)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-23 16:49:48.288: E/AndroidRuntime(437): at dalvik.system.NativeStart.main(Native Method)
04-23 16:49:48.288: E/AndroidRuntime(437): Caused by: android.database.sqlite.SQLiteException: no such column: ‘1’: , while compiling: SELECT _id, display_name FROM view_contacts_restricted WHERE (in_visible_group = ‘1’) ORDER BY display_name COLLATE LOCALIZED ASC
04-23 16:49:48.288: E/AndroidRuntime(437): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentResolver.query(ContentResolver.java:245)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.Activity.managedQuery(Activity.java:1520)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.getContacts(ChatService.java:73)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.checkandImportContacts(ChatService.java:56)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:46)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

You use the wrong chars in your query
Caused by: android.database.sqlite.SQLiteException: no such column: ‘1’
SQLite tries to interpret the ‘1’ as column name since it is no primitive value. Values in SQLite are surrounded by ', column names by " or nothing.
if that group thing is dynamic do it like this:
int group = 1;
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?";
String[] selectionArgs = new String[] { String.valueOf(group) };
The value is automatically wrapped in ' & escaped then. If the value is static you can simply do
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = 1";
String[] selectionArgs = null;

private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
The above retrun all the name and number from from your contact database..

Related

Error in fetching data from database table

I am making an android app. and am trying to fetching data from column, name and score from
the database table but getting this error at run time,
Sorry this application has stopped unexpectedly.
This is my Code from Database Class,
public long addscore(String name, int score)
{
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_score, score);
// Inserting Row
return db.insert(DATABASE_TABLE, null, values);
}
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },,KEY_scoreid + "="
+ rowid,null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
And this is the code of class from where i m trying to
fetch the Data from Database table (Highscore.java),
public class Highscore extends Activity
{
TextView name1,name2,name3,name4,name5,score1,score2,score3,score4,score5;
DBAdapter db1;
Cursor c;
int id;
String n1,n2,n3,n4,n5;
String s1,s2,s3,s4,s5;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
Button backbtn=(Button)findViewById(R.id.backbtn);
OnClickListener listener=new OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Highscore.this,MainActivity.class);
startActivity(i);
finish();
}
};
backbtn.setOnClickListener(listener);
id=1;
name1=(TextView)findViewById(R.id.name1);
score1=(TextView)findViewById(R.id.score1);
db1=new DBAdapter(this);
db1.open();
c=db1.getScore(1);
n1=c.getString(1);
name1.setText(n1);
s1=c.getString(2);
score1.setText(s1);
c=db1.getScore(2);
n2=c.getString(1);
name2.setText(n2);
s2=c.getString(2);
score2.setText(s2);
c=db1.getScore(3);
n3=c.getString(1);
name3.setText(n3);
s3=c.getString(2);
score3.setText(s3);
id++;
c=db1.getScore(4);
n4=c.getString(1);
name4.setText(n4);
s4=c.getString(2);
score4.setText(s4);
id++;
c=db1.getScore(5);
n5=c.getString(1);
name5.setText(n5);
s5=c.getString(2);
score5.setText(s5);
c.deactivate();
c.close();
db1.close();
}
}
This time i am only fetching 5 names and scores.
Here's my Logcat Error,
09-19 12:01:36.046: D/AndroidRuntime(455): Shutting down VM
09-19 12:01:36.046: W/dalvikvm(455): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-19 12:01:36.066: E/AndroidRuntime(455): FATAL EXCEPTION: main
09-19 12:01:36.066: E/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.Highscore}: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:521)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-19 12:01:36.066: E/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at com.example.quizapp.Highscore.onCreate(Highscore.java:59)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-19 12:01:36.066: E/AndroidRuntime(455): ... 11 more
If you people are not getting any thing from my question so please ask..
Please help me to Solve out the Error.
Thanks in Advance
From what I see you problem is not in the database connection, you have some untreated exceptions. You have a NULL pointer exception also in onCreate(Highscore.java:59)
You can do a thing: comment parts of the code until you get a working app(that does nothing) and then uncomment until you find the exact code that crashes the app, it is easy to do and usually you will find the line that is problematic
Good luck
Use this code insted of your.....
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },KEY_scoreid + " ='"
+ rowid + "'",null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}

While clicking search,my application has stopped

I am using searching,to show the listview contents.While clicking the search functionality or type any data,it shows that my application has stopped.
Mainactivity.java
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return mDbHelper.fetchProjectByName(constraint.toString());
}
});
This is my db.java
public Cursor fetchProjectByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID,
CATEGORY_COLUMN_CONTENT},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID,
CATEGORY_COLUMN_CONTENT},
CATEGORY_COLUMN_CONTENT + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Using the db in fetchproject by name i want to search the contents of the listview which will match according to my search option.It shows some logcaterror.
While typing or clicking the search area,it shows my applicaton has stopped.
this is my logcat error.
07-15 12:23:08.688: E/AndroidRuntime(25812): FATAL EXCEPTION: main
07-15 12:23:08.688: E/AndroidRuntime(25812): java.lang.IllegalArgumentException: column 'title' does not exist
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:333)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.widget.SimpleCursorAdapter.swapCursor(SimpleCursorAdapter.java:345)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.widget.CursorAdapter.changeCursor(CursorAdapter.java:309)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.widget.CursorFilter.publishResults(CursorFilter.java:67)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.os.Handler.dispatchMessage(Handler.java:99)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.os.Looper.loop(Looper.java:137)
07-15 12:23:08.688: E/AndroidRuntime(25812): at android.app.ActivityThread.main(ActivityThread.java:5039)
07-15 12:23:08.688: E/AndroidRuntime(25812): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 12:23:08.688: E/AndroidRuntime(25812): at java.lang.reflect.Method.invoke(Method.java:511)
07-15 12:23:08.688: E/AndroidRuntime(25812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-15 12:23:08.688: E/AndroidRuntime(25812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-15 12:23:08.688: E/AndroidRuntime(25812): at dalvik.system.NativeStart.main(Native Method)
Add title column in your query.
mCursor = mDb.query(DATABASE_TABLE_PROJ,
new String[]{CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,
CATEGORY_COLUMN_CONTENT},
null, null, null, null, null);

SQLite Database error while trying to retrive values from database

I have an activity in which I am inserting values to a sqlite table, and then querying the table to get the values.
The activity:
public class TableActivity extends Activity {
TableLayout follow_up_table;
TableRow followup_tr_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
follow_up_table=(TableLayout) findViewById(R.id.follow_up_table);
//---------------Essay Title Table Header-----------------------------------------------
TableRow essay_title_tr_head = new TableRow(this);
essay_title_tr_head.setId(10);
essay_title_tr_head.setBackgroundResource(R.drawable.list_header);
essay_title_tr_head.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView label_essay_title = new TextView(this);
label_essay_title.setId(20);
label_essay_title.setText("Time");
label_essay_title.setTextColor(Color.WHITE);
label_essay_title.setPadding(5,5,5,5);
essay_title_tr_head.addView(label_essay_title);// add the column to the table row here
label_essay_title.setTextSize(12);
TextView label_description = new TextView(this);
label_description.setId(20);
label_description.setText("Student Name");
label_description.setTextColor(Color.WHITE);
label_description.setPadding(5,5,5,5);
essay_title_tr_head.addView(label_description);// add the column to the table row here
label_description.setTextSize(12);
follow_up_table.addView(essay_title_tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
//---------------Essay Title Table Header-----------------------------------------------
//getTime();
// database handler
insertData("Morning", "2013-04-23 10:00:00", "Suresh Kumar");
insertData("Morning", "2013-04-23 11:30:00", "Pravat Das");
insertData("Evening", "2013-04-23 16:16:00", "Namita Roy");
insertData("Evening", "2013-04-23 17:30:00", "Rakesh Mitra");
insertData("After noon", "2013-04-23 10:00:00", "Anil Sarma");
getTime();
}
public void getTime()
{
// database handler
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getTime();
Iterator itr = lables.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
//method to insert data into local database
public void insertData(String timeName, String time, String studentName)
{
DatabaseHandler db = new DatabaseHandler(TableActivity.this);
ContentValues values = new ContentValues();
//db.createDataBase();
values.put("timeName",timeName);
values.put("time",time);
values.put("studentName",studentName);
db.insertValues(timeName, time, studentName);
db.close();
}
}
The database helper class:
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "counselor";
// Labels table name
private static final String TABLE_LABELS = "follow_up";
// Labels Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_time_name = "time_name";
private static final String KEY_time = "time";
private static final String KEY_student_name = "student_name";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE follow_up (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , time_name VARCHAR, time DATETIME, student_name VARCHAR)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
// Create tables again
onCreate(db);
}
public void insertValues(String timeName, String time, String studentName)
{
SQLiteDatabase db = this.getWritableDatabase();
String sql = "INSERT INTO follow_up ( time_name, time, student_name) VALUES ('"+timeName+"', '"+time+"', '"+studentName+"')";
Cursor cursor = db.rawQuery(sql, null); //<< execute here
cursor.moveToFirst();
db.close();
}
//
// /**
// * Getting all labels
// * returns list of labels
// * */
public List<String> getTime(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT time_name FROM follow_up ORDER BY time";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
The error in logcat:
04-24 09:21:18.187: D/dalvikvm(1260): GC_FOR_ALLOC freed 66K, 7% free 2561K/2748K, paused 169ms, total 183ms
04-24 09:21:18.207: I/dalvikvm-heap(1260): Grow heap (frag case) to 3.222MB for 635812-byte allocation
04-24 09:21:18.328: D/dalvikvm(1260): GC_FOR_ALLOC freed 2K, 6% free 3179K/3372K, paused 116ms, total 116ms
04-24 09:21:18.467: D/dalvikvm(1260): GC_CONCURRENT freed <1K, 6% free 3190K/3372K, paused 9ms+27ms, total 141ms
04-24 09:21:19.167: E/CursorWindow(1260): Failed to read row 0, column 1 from a CursorWindow which has 5 rows, 1 columns.
04-24 09:21:19.167: D/AndroidRuntime(1260): Shutting down VM
04-24 09:21:19.167: W/dalvikvm(1260): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-24 09:21:19.197: E/AndroidRuntime(1260): FATAL EXCEPTION: main
04-24 09:21:19.197: E/AndroidRuntime(1260): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ica.dynamictable/com.ica.dynamictable.TableActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.os.Looper.loop(Looper.java:137)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-24 09:21:19.197: E/AndroidRuntime(1260): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): at java.lang.reflect.Method.invoke(Method.java:511)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-24 09:21:19.197: E/AndroidRuntime(1260): at dalvik.system.NativeStart.main(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.database.CursorWindow.nativeGetString(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.database.CursorWindow.getString(CursorWindow.java:434)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.ica.commons.DatabaseHandler.getTime(DatabaseHandler.java:77)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.ica.dynamictable.TableActivity.getTime(TableActivity.java:83)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.ica.dynamictable.TableActivity.onCreate(TableActivity.java:73)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.Activity.performCreate(Activity.java:5104)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-24 09:21:19.197: E/AndroidRuntime(1260): ... 11 more
Actually what I am trying to do is to put all time_name into a list so that I can populate a table using it.
Where am I going wrong?
In your method of DBHelper getTime(), you are using query for getting only one row. Later in that method you are using labels.add(cursor.getString(1));
you should use labels.add(cursor.getString(0)); instead because there is only one row in the Cursor
cursor.getString(1) should be cursor.getString(0) because in query "SELECT time_name FROM follow_up ORDER BY time"; you will get only one data i.e. time_name at index 0 in cursor.getString(0)
SELECT time_name FROM follow_up ORDER BY time
contains only 1 column. Its index is therefore 0. You'd access it with
labels.add(cursor.getString(0));
Or, more cleanly :
int index = cursor.getColumnIndex("time_name");
and
labels.add(cursor.getString(index));
Also, I should add that your if ... do ... while can be replaced by a single while(cursor.moveToNext()) block, as the position of the newly created cursor is always right before first, making the first moveToNext effetively identical to a moveToFirst

Bind Value At Index 1 is Null

In my app, I have a list that shows a record of every patients medical treatments, the list shows their name, date of treatment. I want to be able to click on a specific entry and have it go to the edit screen.
The app adds new entries correctly, it lists the entry correctly but when I select an entry from the list I get the unable to start activity and the message is the Bind Value At Index 1 is null
My code is as follows
To build the list I am choosing from
public void fillMedicalList(String editPatientToGet){
//sql Query
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Medical.MEDICAL_TABLE_NAME );
// build the return columns
String asColumnsToReturn[]= {
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_PATIENTID,
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_PATIENT_GROUP,
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_TREATMENT_DATE,
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_TREATMENT,
Medical.MEDICAL_TABLE_NAME + "." + Medical._ID};
//end of build columns to return
//build the where clause - find entries based on patient id
String valueToFind[] = {editPatientToGet};
//build the cursor
mCursor = queryBuilder.query(mDB, asColumnsToReturn, Medical.MEDICAL_PATIENTID + "=?", valueToFind,
null, null, null);
//manage the cursor
startManagingCursor(mCursor);
//use an adapter to bind the data to the listview
MedicalListAdapter adapter = new MedicalListAdapter(this, mCursor);
ListView av = (ListView) findViewById(R.id.medical_list);
av.setAdapter(adapter);
Now I begin to listen for a click of an item on the list
av.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
final long editMedicalid = id;
String WhatRecordIsIt = String.valueOf(editMedicalid);
Log.i("who is it", WhatRecordIsIt);
Log.d(DEBUG_TAG,WhatRecordIsIt);
editMedical(editMedicalid);
} //end of onClick for an item in the list
}); //end of OnItemClick Listener
} //end of fill PATIENTItem list
At this point my Log.i info shows that it has the correct Record ID.
Now my editMedical(editMedicalid) code is as follows
//we've clicked on a patient in the List list and now we're editing it
public void editMedical(Long id){
String astrArgs[] = {id.toString()};
String EditColumnsToReturn[]={
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_PATIENTID,
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_PATIENT_GROUP,
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_TREATMENT_DATE,
Medical.MEDICAL_TABLE_NAME + "." + Medical.MEDICAL_TREATMENT,
Medical.MEDICAL_TABLE_NAME + "." + Medical._ID};
Cursor c = mDB.query(Medical.MEDICAL_TABLE_NAME, EditColumnsToReturn,
Medical._ID + "=?", astrArgs, null, null, null, null);
c.moveToFirst();
final String strMedicalName =
c.getString(c.getColumnIndex(Medical.MEDICAL_PATIENTID));
Log.i("Patient's Name Is", strMedicalName);
Log.d(DEBUG_TAG,strMedicalName);
final String strMedicalType =
c.getString(c.getColumnIndex(Medical.MEDICAL_PATIENT_GROUP));
Log.i("what group", strMedicalType);
Log.d(DEBUG_TAG,strMedicalType);
final String strMedicalTreatmentDate =
c.getString(c.getColumnIndex(Medical.MEDICAL_TREATMENT_DATE));
Log.i("date", strMedicalTreatmentDate);
Log.d(DEBUG_TAG,strMedicalTreatmentDate);
final String strMedicalTreatment =
c.getString(c.getColumnIndex(Medical.MEDICAL_TREATMENT));
Log.i("treatment was", strMedicalTreatment);
Log.d(DEBUG_TAG,strMedicalTreatment);
final Long MedicalId =
c.getLong(c.getColumnIndex(Medical._ID));
String CurrentPatient = String.valueOf(MedicalId);
Log.i("Patient ID is", CurrentPatient);
Intent editMedical = new Intent(MedicalListActivity.this,
EditMedicalActivity.class);
editMedical.putExtra("patientName", strMedicalName);
editMedical.putExtra("patientGroup", strMedicalType);
editMedical.putExtra("treatmentDate", strMedicalTreatmentDate);
editMedical.putExtra("medicalTreatment", strMedicalTreatment);
String strCurrentPatient = String.valueOf(MedicalId);
editMedical.putExtra("medicalId", strCurrentPatient);
MedicalListActivity.this.startActivity(editMedical);
} //End of getting data needed to edit the record
My log.i shows the correct data being gathered but at this point I get error that it can't launch my EditMedicalActivity because the Bind Value At Index 1 is null
I've read and reread my code and can't find my mistake.
LogCat
02-15 15:33:35.769: E/AndroidRuntime(20339): FATAL EXCEPTION: main
02-15 15:33:35.769: E/AndroidRuntime(20339): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.agmsi.medical/com.agmsi.medical.EditMedicalActivity}: java.lang.IllegalArgumentException: the bind value at index 1 is null
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.os.Handler.dispatchMessage(Handler.java:99)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.os.Looper.loop(Looper.java:130)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.ActivityThread.main(ActivityThread.java:3687)
02-15 15:33:35.769: E/AndroidRuntime(20339): at java.lang.reflect.Method.invokeNative(Native Method)
02-15 15:33:35.769: E/AndroidRuntime(20339): at java.lang.reflect.Method.invoke(Method.java:507)
02-15 15:33:35.769: E/AndroidRuntime(20339): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
02-15 15:33:35.769: E/AndroidRuntime(20339): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-15 15:33:35.769: E/AndroidRuntime(20339): at dalvik.system.NativeStart.main(Native Method)
02-15 15:33:35.769: E/AndroidRuntime(20339): Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:237)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.database.sqlite.SQLiteQuery.bindString(SQLiteQuery.java:185)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:48)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1356)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:330)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:280)
02-15 15:33:35.769: E/AndroidRuntime(20339): at com.agmsi.medical.MedicalListActivity.fillMedicalList(MedicalListActivity.java:85)
02-15 15:33:35.769: E/AndroidRuntime(20339): at com.agmsi.medical.MedicalListActivity.onCreate(MedicalListActivity.java:42)
02-15 15:33:35.769: E/AndroidRuntime(20339): at com.agmsi.medical.EditMedicalActivity.onCreate(EditMedicalActivity.java:41)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-15 15:33:35.769: E/AndroidRuntime(20339): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
02-15 15:33:35.769: E/AndroidRuntime(20339): ... 11 more
Well since the error occurs right after this section, I guess this is the part
Intent editMedical = new Intent(MedicalListActivity.this,
EditMedicalActivity.class);
editMedical.putExtra("patientName", strMedicalName);
editMedical.putExtra("patientGroup", strMedicalType);
editMedical.putExtra("treatmentDate", strMedicalTreatmentDate);
editMedical.putExtra("medicalTreatment", strMedicalTreatment);
String strCurrentPatient = String.valueOf(MedicalId);
editMedical.putExtra("medicalId", strCurrentPatient);
MedicalListActivity.this.startActivity(editMedical);
Right after this the error shows - so I'm not sure if it's something here or elsewhere which is why I posted the code from the two areas that are involved
This is a sqlite (database error).
after looking through your code and comparing it with my own it seems that editPatientToGet which you are passing to the fillMedicalList(String editPatientToGet); is null
your logcat can confirm it on this line:
02-15 15:33:35.769: E/AndroidRuntime(20339): at com.agmsi.medical.MedicalListActivity.fillMedicalList(MedicalListActivity.java:85)
The stacktrace makes it look like the following line is the problem:
Cursor c = mDB.query(Medical.MEDICAL_TABLE_NAME, EditColumnsToReturn,
Medical._ID + "=?", astrArgs, null, null, null, null);
Are you extending a codebase? You do use different styles.
Perhaps the other style works for you:
Cursor c = queryBuilder.query(mDB, EditColumnsToReturn, Medical._ID + "=?", astrArgs,
null, null, null);

android sqlite, close() was nevere explicitly called [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
/i am writing probgram that should take xml file and parse it to database.
Database worked witohut crashes, but with close() error, before i tried to implement update function, after that program alwayes crashes.
i decided to use update to prevent dublication and update records ^_^ (is there better way?)
bedies i have only one activity, using clothing database onDestroy does not help.
And appiared Fatal exeption ( full logcat in the bottom)
Unable to start activity
ComponentInfo{com.s1042512.electionvoter/com.s1042512.electionvoter.MainActivity}:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
main class
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.s1042512.electionvoter.ImageLoader;
import com.s1042512.electionvoter.XMLParser;
import com.s1042512.electionvoter.Candidate;
import com.s1042512.electionvoter.DatabaseHandler;
import com.s1042512.electionvoter.R;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.ImageView;
public class MainActivity extends Activity {
static final String URL = "http://www.inf.ed.ac.uk/teaching/courses/selp/elections/election.xml";
// XML node keys
static final String KEY_CANDIDATE = "candidate"; // parent node
static final String KEY_PHOTO = "photograph";
static final String KEY_NAME = "name";
static final String KEY_OFFICE = "office";
static final String KEY_PROMISES = "promise";
static final String KEY_STAT = "statement";
private DatabaseHandler db;
public void onDestroy(){
db.close();
super.onDestroy();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
Candidate test = new Candidate("Test", "Test's office", "Test's photo", "Test's promises", "Test's statement", 1,5);
db.addCandidate(test);
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_CANDIDATE);
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
NodeList prm = null;
String prom = "";
prm = doc.getElementsByTagName("promise");
if (db.getCandidatesCount() != 0) {
List<Candidate> clist = db.getAllCandidates();
boolean checkname = clist.contains(db.getCandidate(parser
.getValue(e, KEY_NAME)));
for (int j = 0; j < prm.getLength(); j++) {
prom += parser.getValue(e, KEY_PROMISES, j) + "\n";
}
if (!checkname) {
Log.d("Insert: ", "Inserting ..");
db.addCandidate(new Candidate(parser.getValue(e, KEY_NAME),
parser.getValue(e, KEY_OFFICE), parser.getValue(e,
KEY_PHOTO), prom, parser.getValue(e,
KEY_STAT)));
} else {
Log.d("Update: ", "Updating candidate ");
Candidate cand = db.getCandidate(parser.getValue(e,
KEY_NAME));
Candidate update_cand = new Candidate(parser.getValue(e,
KEY_NAME), parser.getValue(e, KEY_OFFICE),
parser.getValue(e, KEY_PHOTO), prom,
parser.getValue(e, KEY_STAT), cand.get_active(),
cand.get_ranking());
db.updateCandidate(update_cand);
}
}
else{
Log.d("Insert: ", "Inserting ..");
db.addCandidate(new Candidate(parser.getValue(e, KEY_NAME),
parser.getValue(e, KEY_OFFICE), parser.getValue(e,
KEY_PHOTO), prom, parser.getValue(e,
KEY_STAT)));
}
}
Log.d("Reading: ", "Reading all candidates..");
List<Candidate> candidates = db.getAllCandidates();
for (Candidate cn : candidates) {
String log = "Name: "+cn.get_name()+" ,Office: " + cn.get_office() + " , Photo: " + cn.get_photograph()
+ " , Promisses: " + cn.get_promises()+ " , Statment: " + cn.get_statment();
// Writing Candidates to log
Log.d("Name: ", log);
}
}
}
helper class
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ElectionCandidates";
// Candidates table name
private static final String TABLE_CANDIDATES = "candidates";
// Candidates Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_OFFICE = "office";
private static final String KEY_PHOTO = "photograph";
private static final String KEY_PROMISSES = "promisses";
private static final String KEY_STATMENT = "statment";
private static final String KEY_ACTIVE = "active";
private static final String KEY_RANKING = "ranking";
private SQLiteDatabase db;
private Cursor cursor;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CANDIDATES_TABLE = "CREATE TABLE " + TABLE_CANDIDATES
+ "(" + KEY_NAME + " TEXT," + KEY_OFFICE + " TEXT," + KEY_PHOTO
+ " TEXT," + KEY_PROMISSES + " TEXT," + KEY_STATMENT + " TEXT,"
+ KEY_ACTIVE + " TEXT," + KEY_RANKING + " TEXT" + ")";
db.execSQL(CREATE_CANDIDATES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CANDIDATES);
// Create tables again
onCreate(db);
}
void addCandidate(Candidate candidate) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, candidate.get_name()); // Candidate Name
values.put(KEY_OFFICE, candidate.get_office()); // Candidate Phone
values.put(KEY_PHOTO, candidate.get_photograph());
values.put(KEY_PROMISSES, candidate.get_promises());
values.put(KEY_STATMENT, candidate.get_statment());
values.put(KEY_ACTIVE, 1);
values.put(KEY_RANKING, 0);
// Inserting Row
db.insert(TABLE_CANDIDATES, null, values);
db.close(); // Closing database connection
}
Candidate getCandidate(String name) {
db = this.getReadableDatabase();
cursor = db.query(TABLE_CANDIDATES,
new String[] { KEY_NAME, KEY_OFFICE, KEY_PHOTO, KEY_PROMISSES,
KEY_STATMENT, KEY_ACTIVE, KEY_RANKING }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Candidate candidate = new Candidate(cursor.getString(0),
cursor.getString(1), cursor.getString(2), cursor.getString(3),
cursor.getString(4), Integer.parseInt(cursor.getString(5)), Integer.parseInt(cursor.getString(6)));
// return candidate
db.close();
cursor.close();
return candidate;
}
public List<Candidate> getAllCandidates() {
List<Candidate> candidateList = new ArrayList<Candidate>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CANDIDATES;
db = this.getReadableDatabase();
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Candidate candidate = new Candidate();
candidate.set_name(cursor.getString(0));
candidate.set_office(cursor.getString(1));
candidate.set_photograph(cursor.getString(2));
candidate.set_promises(cursor.getString(3));
candidate.set_statment(cursor.getString(4));
candidate.set_active(Integer.parseInt(cursor.getString(5)));
candidate.set_ranking(Integer.parseInt(cursor.getString(6)));
// Adding candidate to list
candidateList.add(candidate);
} while (cursor.moveToNext());
}
// return candidate list
db.close();
cursor.close();
return candidateList;
}
public int updateCandidate(Candidate candidate) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, candidate.get_name()); // Candidate Name
values.put(KEY_OFFICE, candidate.get_office()); // Candidate Phone
values.put(KEY_PHOTO, candidate.get_photograph());
values.put(KEY_PROMISSES, candidate.get_promises());
values.put(KEY_STATMENT, candidate.get_statment());
values.put(KEY_ACTIVE, candidate.get_active());
values.put(KEY_RANKING, candidate.get_active());
// updating row
return db.update(TABLE_CANDIDATES, values, KEY_NAME + " = ?",
new String[] { String.valueOf(candidate.get_name()) });
}
// Deleting single candidate
public void deleteCandidate(Candidate candidate) {
db = this.getWritableDatabase();
db.delete(TABLE_CANDIDATES, KEY_NAME + " = ?",
new String[] { String.valueOf(candidate.get_name()) });
db.close();
}
// Getting candidates Count
public int getCandidatesCount() {
String countQuery = "SELECT * FROM " + TABLE_CANDIDATES;
db = this.getReadableDatabase();
cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
// return count
return count;
}
}
logcat output
12-13 01:36:25.359: D/I was there(338): parsing
12-13 01:36:25.428: D/AndroidRuntime(338): Shutting down VM
12-13 01:36:25.428: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-13 01:36:25.479: D/dalvikvm(338): GC_FOR_MALLOC freed 3868 objects / 251528 bytes in 53ms
12-13 01:36:25.488: E/Cursor(338): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/com.s1042512.electionvoter/databases/ElectionCandidates, table = candidates, query = SELECT name, office, photograph, promisses, statment, active, ranking FROM candidates WHERE name=?
12-13 01:36:25.488: E/Cursor(338): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
12-13 01:36:25.488: E/Cursor(338): at android.database.sqlite.SQLiteCursor.<init>(SQLiteCursor.java:210)
12-13 01:36:25.488: E/Cursor(338): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:53)
12-13 01:36:25.488: E/Cursor(338): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
12-13 01:36:25.488: E/Cursor(338): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1229)
12-13 01:36:25.488: E/Cursor(338): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184)
12-13 01:36:25.488: E/Cursor(338): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1264)
12-13 01:36:25.488: E/Cursor(338): at com.s1042512.electionvoter.DatabaseHandler.getCandidate(DatabaseHandler.java:80)
12-13 01:36:25.488: E/Cursor(338): at com.s1042512.electionvoter.MainActivity.onCreate(MainActivity.java:58)
12-13 01:36:25.488: E/Cursor(338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-13 01:36:25.488: E/Cursor(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-13 01:36:25.488: E/Cursor(338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-13 01:36:25.488: E/Cursor(338): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-13 01:36:25.488: E/Cursor(338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-13 01:36:25.488: E/Cursor(338): at android.os.Handler.dispatchMessage(Handler.java:99)
12-13 01:36:25.488: E/Cursor(338): at android.os.Looper.loop(Looper.java:123)
12-13 01:36:25.488: E/Cursor(338): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-13 01:36:25.488: E/Cursor(338): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 01:36:25.488: E/Cursor(338): at java.lang.reflect.Method.invoke(Method.java:521)
12-13 01:36:25.488: E/Cursor(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-13 01:36:25.488: E/Cursor(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-13 01:36:25.488: E/Cursor(338): at dalvik.system.NativeStart.main(Native Method)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): Releasing statement in a finalizer. Please ensure that you explicitly call close() on your cursor: SELECT name, office, photograph, promisses, statment, active, ranking FROM candidates WHERE name=?
12-13 01:36:25.508: W/SQLiteCompiledSql(338): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:62)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1229)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1264)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at com.s1042512.electionvoter.DatabaseHandler.getCandidate(DatabaseHandler.java:80)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at com.s1042512.electionvoter.MainActivity.onCreate(MainActivity.java:58)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.os.Handler.dispatchMessage(Handler.java:99)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.os.Looper.loop(Looper.java:123)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at java.lang.reflect.Method.invoke(Method.java:521)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-13 01:36:25.508: W/SQLiteCompiledSql(338): at dalvik.system.NativeStart.main(Native Method)
12-13 01:36:25.518: E/AndroidRuntime(338): FATAL EXCEPTION: main
12-13 01:36:25.518: E/AndroidRuntime(338): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.s1042512.electionvoter/com.s1042512.electionvoter.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:99)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-13 01:36:25.518: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 01:36:25.518: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:521)
12-13 01:36:25.518: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-13 01:36:25.518: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-13 01:36:25.518: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
12-13 01:36:25.518: E/AndroidRuntime(338): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
12-13 01:36:25.518: E/AndroidRuntime(338): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
12-13 01:36:25.518: E/AndroidRuntime(338): at com.s1042512.electionvoter.DatabaseHandler.getCandidate(DatabaseHandler.java:87)
12-13 01:36:25.518: E/AndroidRuntime(338): at com.s1042512.electionvoter.MainActivity.onCreate(MainActivity.java:58)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-13 01:36:25.518: E/AndroidRuntime(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-13 01:36:25.518: E/AndroidRuntime(338): ... 11 more
12-13 01:36:25.529: E/Database(338): close() was never explicitly called on database '/data/data/com.s1042512.electionvoter/databases/ElectionCandidates'
12-13 01:36:25.529: E/Database(338): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
12-13 01:36:25.529: E/Database(338): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1810)
12-13 01:36:25.529: E/Database(338): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:817)
12-13 01:36:25.529: E/Database(338): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:851)
12-13 01:36:25.529: E/Database(338): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:844)
12-13 01:36:25.529: E/Database(338): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:540)
12-13 01:36:25.529: E/Database(338): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
12-13 01:36:25.529: E/Database(338): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
12-13 01:36:25.529: E/Database(338): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:158)
12-13 01:36:25.529: E/Database(338): at com.s1042512.electionvoter.DatabaseHandler.getCandidate(DatabaseHandler.java:78)
12-13 01:36:25.529: E/Database(338): at com.s1042512.electionvoter.MainActivity.onCreate(MainActivity.java:58)
12-13 01:36:25.529: E/Database(338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-13 01:36:25.529: E/Database(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-13 01:36:25.529: E/Database(338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-13 01:36:25.529: E/Database(338): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-13 01:36:25.529: E/Database(338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-13 01:36:25.529: E/Database(338): at android.os.Handler.dispatchMessage(Handler.java:99)
12-13 01:36:25.529: E/Database(338): at android.os.Looper.loop(Looper.java:123)
12-13 01:36:25.529: E/Database(338): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-13 01:36:25.529: E/Database(338): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 01:36:25.529: E/Database(338): at java.lang.reflect.Method.invoke(Method.java:521)
12-13 01:36:25.529: E/Database(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-13 01:36:25.529: E/Database(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-13 01:36:25.529: E/Database(338): at dalvik.system.NativeStart.main(Native Method)
I think your error is pretty simple.
Is your 153 in DatabaseHandler the line including the following code?
return cursor.getCount();
In this line, you are accessing the cursor-Object, that has been closed just before that.
According to the API, the cursor is invalid after closing.
Try changing the getCandidatesCount()-Method to:
public int getCandidatesCount() {
String countQuery = "SELECT * FROM " + TABLE_CANDIDATES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int candidatesCount = cursor.getCount();
cursor.close();
// return count
return candidatesCount;
}
PS: Is there any reason for not closing the Cursor in the methods getCandidate(..) and getAllCandidates() ?

Categories