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
Related
I have spinner in Activity and edittext's. When i run the app I'm getting warning of nullPointerException.I dosen't retrieve the SQLite data in edit text in onCreate().Can someone help me.
Here is my code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_entry);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
spinner_searchByEmpName = (Spinner)findViewById(R.id.searchByEmpName);
loadSerachBYProject() ;
spinner_searchByEmpName.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedEmployeeName = spinner_searchByEmpName.getSelectedItem().toString().trim();
System.out.println("selectedProjectName " + selectedEmployeeName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
etEmpName=(EditText)findViewById(R.id.Delete_editText_StaffEmployee_Name);
etDepartment=(EditText)findViewById(R.id.Delete_editText_Department);
etDesignation=(EditText)findViewById(R.id.Delete_editText_Designation);
try {
Cursor cursor = db.rawQuery("SELECT staff_employee_id, staff_emp_name, department, designation FROM employee_details WHERE staff_emp_name = ?",
new String[] { "" + selectedEmployeeName });
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void loadSerachBYProject()
{
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> projectsName = databaseHelper.getAllEmployeeName();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, projectsName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_searchByEmpName.setAdapter(dataAdapter);
}
}
Thanks in Advance.
Here is My Log cat error info
06-26 18:08:09.073: W/System.err(601): java.lang.NullPointerException
06-26 18:08:09.083: W/System.err(601): at com.employee_review.Update_Entry.onCreate(Update_Entry.java:68)
06-26 18:08:09.083: W/System.err(601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-26 18:08:09.103: W/System.err(601): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 18:08:09.103: W/System.err(601): at android.os.Looper.loop(Looper.java:123)
06-26 18:08:09.113: W/System.err(601): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-26 18:08:09.123: W/System.err(601): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 18:08:09.133: W/System.err(601): at java.lang.reflect.Method.invoke(Method.java:507)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-26 18:08:09.133: W/System.err(601): at dalvik.system.NativeStart.main(Native Method)
Try this , i guess
if(cursor!=null){
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
db is never initialized. It must be initialized in onCreate(), as that's the first method that is run in an Activity. I see this:
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
I'm guessing you really should have this:
databaseHelper = new DatabaseHelper(this);
db=databaseHelper.getReadableDatabase();
I would like to implement a progress dialog when the database load the data for the first time.
this is my code
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(ENG_FRA_TABLE_CREATE);
loadDictionaryEngFra();
new InitDB().execute();
}
public class InitDB extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(mHelperContext, "", "Wait", true);
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
If i try to run the app with this progress dialog, it throw this error list
04-18 23:16:30.886: E/SQLiteLog(26059): (1) no such table: ENG_FRAdictionary
04-18 23:16:30.896: E/SQLiteDatabase(26059): Error inserting suggest_text_1=abbey suggest_text_2=n. a monastery ruled by an abbot
04-18 23:16:30.896: E/SQLiteDatabase(26059): android.database.sqlite.SQLiteException: no such table: ENG_FRAdictionary (code 1): , while compiling: INSERT INTO ENG_FRAdictionary(suggest_text_1,suggest_text_2) VALUES (?,?)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:686)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1573)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1445)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.addWordEngFra(DictionaryDatabaseEngFra.java:238)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.loadWordsEngFra(DictionaryDatabaseEngFra.java:218)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.access$1(DictionaryDatabaseEngFra.java:208)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper$1.run(DictionaryDatabaseEngFra.java:200)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at java.lang.Thread.run(Thread.java:856)
04-18 23:16:30.896: E/DictionaryDatabaseEngFra(26059): unable to add word: abbey
04-18 23:16:30.896: W/dalvikvm(26059): threadid=14: thread exiting with uncaught exception (group=0x41d24930)
04-18 23:16:30.896: E/AndroidRuntime(26059): FATAL EXCEPTION: Thread-51326
04-18 23:16:30.896: E/AndroidRuntime(26059): java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.example.searchtoto/databases/dictionaryEngFra
04-18 23:16:30.896: E/AndroidRuntime(26059): at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
04-18 23:16:30.896: E/AndroidRuntime(26059): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1543)
04-18 23:16:30.896: E/AndroidRuntime(26059): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1445)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.addWordEngFra(DictionaryDatabaseEngFra.java:238)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.loadWordsEngFra(DictionaryDatabaseEngFra.java:218)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.access$1(DictionaryDatabaseEngFra.java:208)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper$1.run(DictionaryDatabaseEngFra.java:200)
04-18 23:16:30.896: E/AndroidRuntime(26059): at java.lang.Thread.run(Thread.java:856)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): Search suggestions query threw an exception.
04-18 23:16:30.996: W/SuggestionsAdapter(26059): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.view.ViewRootImpl.setView(ViewRootImpl.java:804)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.Dialog.show(Dialog.java:282)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.ProgressDialog.show(ProgressDialog.java:116)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.ProgressDialog.show(ProgressDialog.java:99)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper$InitDB.onPreExecute(DictionaryDatabaseEngFra.java:174)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.AsyncTask.execute(AsyncTask.java:534)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.onCreate(DictionaryDatabaseEngFra.java:162)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra.query(DictionaryDatabaseEngFra.java:113)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra.getWordMatchesEngFra(DictionaryDatabaseEngFra.java:96)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryProviderEngFra.getSuggestions(DictionaryProviderEngFra.java:107)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryProviderEngFra.query(DictionaryProviderEngFra.java:81)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentProvider.query(ContentProvider.java:652)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentProvider$Transport.query(ContentProvider.java:189)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentResolver.query(ContentResolver.java:375)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentResolver.query(ContentResolver.java:318)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.SearchManager.getSuggestions(SearchManager.java:930)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.widget.SuggestionsAdapter.runQueryOnBackgroundThread(SuggestionsAdapter.java:200)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.widget.CursorFilter.performFiltering(CursorFilter.java:49)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.Handler.dispatchMessage(Handler.java:99)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.Looper.loop(Looper.java:137)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.HandlerThread.run(HandlerThread.java:60)
whitout the implementation of the progress dialog, the app run fine
this is the activity
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
/**
* Contains logic to return specific words from the dictionary, and
* load the dictionary table when it needs to be created.
*/
public class DictionaryDatabaseEngFra extends SearchableDictionaryEngFra{
private static final String TAG = "DictionaryDatabaseEngFra";
//The columns we'll include in the dictionary table
public static final String KEY_WORD_ENG_FRA = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String KEY_DEFINITION_ENG_FRA = SearchManager.SUGGEST_COLUMN_TEXT_2;
private static final String DATABASE_NAME = "dictionaryEngFra";
private static final String ENG_FRA_TABLE = "ENG_FRAdictionary";
private static final int DATABASE_VERSION = 2;
private final DictionaryOpenHelper mDatabaseOpenHelper;
private static final HashMap<String,String> mColumnMapEngFra = buildColumnMapEngFra();
static File ENG_FRA = new File(Environment.getExternalStorageDirectory().getPath() + "/dic/dictionary/engfra./", "eng_fra.txt");
/**
* Constructor
* #param context The Context within which to work, used to create the DB
*/
public DictionaryDatabaseEngFra(Context context) {
mDatabaseOpenHelper = new DictionaryOpenHelper(context);
}
/**
* Builds a map for all columns that may be requested, which will be given to the
* SQLiteQueryBuilder. This is a good way to define aliases for column names, but must include
* all columns, even if the value is the key. This allows the ContentProvider to request
* columns w/o the need to know real column names and create the alias itself.
*/
private static HashMap<String,String> buildColumnMapEngFra() {
HashMap<String,String> mapEngFra = new HashMap<String,String>();
mapEngFra.put(KEY_WORD_ENG_FRA, KEY_WORD_ENG_FRA);
mapEngFra.put(KEY_DEFINITION_ENG_FRA, KEY_DEFINITION_ENG_FRA);
mapEngFra.put(BaseColumns._ID, "rowid AS " +
BaseColumns._ID);
mapEngFra.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " +
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
mapEngFra.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
return mapEngFra;
}
public Cursor getWordEngFra(String rowId, String[] columns) {
String selection = "rowid = ?";
String[] selectionArgs = new String[] {rowId};
return query(selection, selectionArgs, columns);
}
public Cursor getWordMatchesEngFra(String query, String[] columns) {
String selection = KEY_WORD_ENG_FRA + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
/* The SQLiteBuilder provides a map for all possible columns requested to
* actual columns in the database, creating a simple column alias mechanism
* by which the ContentProvider does not need to know the real column names
*/
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(ENG_FRA_TABLE);
builder.setProjectionMap(mColumnMapEngFra);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
/**
* This creates/opens the database.
*/
private static class DictionaryOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
/* Note that FTS3 does not support column constraints and thus, you cannot
* declare a primary key. However, "rowid" is automatically used as a unique
* identifier, so when making requests, we will use "_id" as an alias for "rowid"
*/
private static final String ENG_FRA_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + ENG_FRA_TABLE +
" USING fts3 (" +
KEY_WORD_ENG_FRA + ", " +
KEY_DEFINITION_ENG_FRA + ");";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(ENG_FRA_TABLE_CREATE);
loadDictionaryEngFra();
new InitDB().execute();
}
public class InitDB extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(mHelperContext, "", "Wait", true);
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
/**
* Starts a thread to load the database table with words
*/
private void loadDictionaryEngFra() {
new Thread(new Runnable() {
public void run() {
try {
loadWordsEngFra();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadWordsEngFra() throws IOException {
Log.d(TAG, "Loading words eng_fra...");
FileInputStream fileInputStream = new FileInputStream(ENG_FRA);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2) continue;
long id = addWordEngFra(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
/**
* Add a word to the dictionary.
* #return rowId or -1 if failed
*/
public long addWordEngFra(String word, String definition) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_WORD_ENG_FRA, word);
initialValues.put(KEY_DEFINITION_ENG_FRA, definition);
return mDatabase.insert(ENG_FRA_TABLE, null, initialValues);
}
/**
* Add a word to the dictionary.
* #return rowId or -1 if failed
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + ENG_FRA_TABLE);
onCreate(db);
}
}
}
This looks like an SQL error.
04-18 23:16:30.896: E/SQLiteDatabase(26059): Error inserting suggest_text_1=abbey suggest_text_2=n. a monastery ruled by an abbot
04-18 23:16:30.896: E/SQLiteDatabase(26059): android.database.sqlite.SQLiteException: no such table: ENG_FRAdictionary (code 1): , while compiling: INSERT INTO ENG_FRAdictionary(suggest_text_1,suggest_text_2) VALUES (?,?)
It doesn't look like your ENG_FRAdictionary table exists.
The problem is in your sqlite db. I can't see a problem with progress dialog
Check your db creation statement and table names. Also check the sqlitehelper class
And let us know what happens
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'm trying to code a simple randomizer app. I had the randomizer button working, but then I changed some code (which I thought was irrelevant to the randomizer button) and it started crashing and getting the "IllegalStateException: Could not execute method of the activity" error. From what I can tell, this error is very specific to what the code is, because I could not find any answers that fit my code.
package com.example.randomgamechooser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
}
public void chooseGame (View view) {
GameList dbUtil = new GameList(this);
dbUtil.open();
String string = dbUtil.getRandomEntry();
//TextView textView = new TextView(this);
TextView textView = (TextView) findViewById(R.id.chosenbox);
textView.setTextSize(40);
textView.setText(string);
//setContentView (textView);
dbUtil.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
//starts the Game Selection activity
public void openGames (View view) {
Intent intent = new Intent(this, GameSelction.class);
startActivity(intent);
}
}
And this is the referenced GameList class
package com.example.randomgamechooser;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Random;
public class GameList {
private static final String TAG = "GameList";
//database name
private static final String DATABASE_NAME = "game_list";
//database version
private static final int DATABASE_VERSION = 1;
//table name
private static final String DATABASE_TABLE = "game_list";
//table columns
public static final String KEY_NAME = "name";
public static final String KEY_GENRE = "genre";
public static final String KEY_ROWID = "_id";
//database creation sql statement
private static final String CREATE_GAME_TABLE =
"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME +" text not null, " + KEY_GENRE + " text not null);";
//Context
private final Context mCtx;
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
//Inner private class. Database Helper class for creating and updating database.
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// onCreate method is called for the 1st time when database doesn't exists.
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_GAME_TABLE);
db.execSQL(CREATE_GAME_TABLE);
}
//onUpgrade method is called when database version changes.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
}
}
//Constructor - takes the context to allow the database to be opened/created
//#param ctx the Context within which to work
public GameList(Context ctx) {
this.mCtx = ctx;
}
//This method is used for creating/opening connection
//#return instance of GameList
//#throws SQLException
public GameList open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
//This method is used for closing the connection.
public void close() {
mDbHelper.close();
}
//This method is used to create/insert new game.
//#param name
// #param genre
// #return long
public long createGame(String name, String genre) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_GENRE, genre);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
// This method will delete game.
// #param rowId
// #return boolean
public static boolean deleteGame(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// This method will return Cursor holding all the games.
// #return Cursor
public Cursor fetchAllGames() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_GENRE}, null, null, null, null, null);
}
// This method will return Cursor holding the specific game.
// #param id
// #return Cursor
// #throws SQLException
public Cursor fetchGame(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_GENRE}, KEY_ROWID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public int getAllEntries()
{
Cursor cursor = mDb.rawQuery(
"SELECT COUNT(name) FROM game_list", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
public String getRandomEntry()
{
//id = getAllEntries();
Random random = new Random();
int rand = random.nextInt(getAllEntries());
if(rand == 0)
++rand;
Cursor cursor = mDb.rawQuery(
"SELECT name FROM game_list WHERE _id = " + rand, null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);
}
// This method will update game.
// #param id
// #param name
// #param standard
// #return boolean
public boolean updateGame(int id, String name, String standard) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_GENRE, standard);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
and here is the error log
07-31 14:50:45.215: D/AndroidRuntime(280): Shutting down VM
07-31 14:50:45.215: W/dalvikvm(280): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-31 14:50:45.236: E/AndroidRuntime(280): FATAL EXCEPTION: main
07-31 14:50:45.236: E/AndroidRuntime(280): java.lang.IllegalStateException: Could not execute method of the activity
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2072)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-31 14:50:45.236: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: java.lang.reflect.InvocationTargetException
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.MainScreen.chooseGame(MainScreen.java:23)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2067)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 11 more
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Read the stacktrace carefuly. Answer is at the last "Caused by" exception;
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Query in method getRandomEntry() returns empty result, while you read from the first position.
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..