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);
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 have an error in a progress bar.
This is a code:
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
private int progressStatus = 0;
private Handler handler = new Handler();
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Button mvc;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;
private ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mvc = (Button) findViewById(R.id.button1);
mvc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
public void run() {
while (progressStatus < 1000) {
Random r = new Random();
int i1 = r.nextInt(1000);
if (i1 > progressStatus){
progressStatus = i1;
}
else {
progressStatus = progressStatus;
}
// Update the progress bar and display the current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds. Just to display the progress slowly
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
This is a logcat:
02-15 12:14:14.102: E/MoreInfoHPW_ViewGroup(21179): Parent view is not a TextView
02-15 12:14:14.142: D/AndroidRuntime(21179): Shutting down VM
02-15 12:14:14.142: W/dalvikvm(21179): threadid=1: thread exiting with uncaught exception (group=0x418ca898)
02-15 12:14:14.142: E/AndroidRuntime(21179): FATAL EXCEPTION: main
02-15 12:14:14.142: E/AndroidRuntime(21179): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.BluetoothChat/com.example.android.BluetoothChat.BluetoothC hat}: java.lang.NullPointerException
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.ActivityThread.access$700(ActivityThread.java:159)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.os.Handler.dispatchMessage(Handler.java:99)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.os.Looper.loop(Looper.java:137)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-15 12:14:14.142: E/AndroidRuntime(21179): at java.lang.reflect.Method.invokeNative(Native Method)
02-15 12:14:14.142: E/AndroidRuntime(21179): at java.lang.reflect.Method.invoke(Method.java:525)
02-15 12:14:14.142: E/AndroidRuntime(21179): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
02-15 12:14:14.142: E/AndroidRuntime(21179): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
02-15 12:14:14.142: E/AndroidRuntime(21179): at dalvik.system.NativeStart.main(Native Method)
02-15 12:14:14.142: E/AndroidRuntime(21179): Caused by: java.lang.NullPointerException
02-15 12:14:14.142: E/AndroidRuntime(21179): at com.example.android.BluetoothChat.BluetoothChat.onCreate(BluetoothChat.java:98)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.Activity.performCreate(Activity.java:5372)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
02-15 12:14:14.142: E/AndroidRuntime(21179): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
02-15 12:14:14.142: E/AndroidRuntime(21179): ... 11 more
02-15 12:14:16.534: I/Process(21179): Sending signal. PID: 21179 SIG: 9
the application does not start, can anyone help me understand the problem? Thank you!
P.S if I remove the button still works perfectly.
In onCreate(), Need to call
setContentView(R.layout.activity_main);
or your layout name -the xml where your "button1" is...
before
mvc = (Button) findViewById(R.id.button1);
It helps your activity to identify its layout and where to look for the components with findViewById
Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy.
http://developer.android.com/reference/android/app/Activity.html#setContentView(android.view.View)
http://bloggerinme.wordpress.com/2011/12/10/android-programming-setcontentview/
Add
progressBar = new ProgressBar(this);
in your onCreate method. You have declared a variable but isn't initialized it. And you should have use
setContentView();
to set the layout for the activity. Here is the doc for that setContentView
Line drawn from doc is :-
Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarchy.
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'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..