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() ?
Related
I'm fairly new to Android and am having an issue with fetching data from my database. I have an activity class which calls the database helper to get a list of questions according to a particular category. The database should then put all of the questions into an ArrayList and return them. The error seems to be occurring when I try and get the first question in the list of questions using:
Question question = questions.get(0);
Here is the relevant method in the activity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atomic_structure_questions);
DatabaseHelper database = new DatabaseHelper(getApplicationContext());
List<Question> questions = database.getQuestions(1);
Question question = questions.get(0);
TextView questionText = (TextView) findViewById(R.id.QuestionText);
questionText.setText(question.getText());
}
Database Helper:
// Get All The Question From Database For A Specific Category And Put Them Into A List Of Question
public List<Question> getQuestions(int category) {
List<Question> questions = new ArrayList<Question>();
String selectQuery = "SELECT * FROM " + TABLE_QUESTION +
" WHERE " + KEY_CATEGORY_ID + " = '" + category + "'";
Log.e(LOG, selectQuery);
database = this.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
// Loops Through The Database To Get All Question Matching Category
do {
Question question = new Question();
question.setId(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ID)));
question.setNumber(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUMBER)));
question.setText(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_TEXT)));
question.setMarks(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_MARKS)));
question.setAnswer(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ANSWER)));
question.setMC1(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC1)));
question.setMC2(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC2)));
question.setMC3(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC3)));
question.setMC4(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC4)));
// Add The Question To The List Of Question
questions.add(question);
} while (cursor.moveToNext());
}
return questions;
}
Finally, here is the logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.revision.aschemistry/com.revision.aschemistry.AtomicStructureQuestions}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.revision.aschemistry.AtomicStructureQuestions.onCreate(AtomicStructureQuestions.java:26)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Any help is much appreciated, thanks in advance.
It seems your ArrayList Question is Empty. So just check size before getting data from it.
List<Question> questions = database.getQuestions(1);
if(!questions.isEmpty())
{
Question question = questions.get(0);
}else
{
Log.e("LOG","questions is Empty")
}
Also check Cursor size in your getQuestions() method from DatabaseHelper class.
Obviously you can use:
if(!questions.isEmpty())
To avoid the the ArrayIndexOutOfBounds Exception. But I guess that dosen't Solve our problem dose it?
I hope our solution here is to read the data properly and then retrieve the data using the get() method of Arraylist.
There needs to be a check before reading the data. Please check if the data are feed properly first and then go for getting them. I would like to suggest some posts you can follow to get idea about Databases.
http://www.vogella.com/tutorials/AndroidSQLite/article.html
http://infobloggall.com/2014/05/06/sqlite-database-example
Also the developer site.
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;
}
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
I am getting a NullPointerException in my SQLite database. I am calling the DatabaseHelper class in Results.java by doing this:
public class Results extends Activity {
...
DatabaseHelper dh;
public void onCreate(Bundle savedInstanceState) {
...
dh = new DatabaseHelper(this);
}
public void showResults() {
...
dh.insert(1, score, percentage);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DB_NAME = "test1";
private static final String DB_PATH = "/data/data/com.example.test/databases/";
private static final String TABLE = "HighscoresList";
// Table columns names.
private static final String RANK = "rank";
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
private SQLiteDatabase myDB;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
myDB = getWritableDatabase(); //Line 25
}
//Insert new record.
public long insert(int rank, long score, int percentage) {
ContentValues values = new ContentValues();
values.put(RANK, rank);
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return myDB.insert(TABLE, null, values);
}
//Delete record.
public boolean delete(long score) {
//Need this?
return true;
}
public void openDatabase() throws SQLException {
//Open the database.
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public SQLiteDatabase getDatabase(){
return this.myDB;
}
public synchronized void close() {
if(myDB != null) {
myDB.close();
}
super.close();
}
public void onCreate(SQLiteDatabase db) {
myDB.execSQL("CREATE TABLE " + TABLE + " (" //Line 62
+ RANK + " INTEGER,"
+ SCORE + " LONG,"
+ PERCENTAGE + " INTEGER"
+ ");");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
LogCat output
12-18 22:01:53.210: E/AndroidRuntime(6313): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Results}: java.lang.NullPointerException
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.os.Looper.loop(Looper.java:137)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.main(ActivityThread.java:4745)
12-18 22:01:53.210: E/AndroidRuntime(6313): at java.lang.reflect.Method.invokeNative(Native Method)
12-18 22:01:53.210: E/AndroidRuntime(6313): at java.lang.reflect.Method.invoke(Method.java:511)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-18 22:01:53.210: E/AndroidRuntime(6313): at dalvik.system.NativeStart.main(Native Method)
12-18 22:01:53.210: E/AndroidRuntime(6313): Caused by: java.lang.NullPointerException
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.example.test.DatabaseHelper.onCreate(DatabaseHelper.java:62)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.example.test.DatabaseHelper.<init>(DatabaseHelper.java:25)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.example.test.Results.onCreate(Results.java:33)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.Activity.performCreate(Activity.java:5008)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-18 22:01:53.210: E/AndroidRuntime(6313): ... 11 more
What is causing the NPE?
Also, any help on code structure for this SQLite highscores I am trying to implement would be helpful as well.
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..