Sqlite database query writing - android

I am trying to write a query for retrieving data from SQLite database. I wanted to print the result of a query in a text box. So I used a getint() method for the cursor. Below is my code. It does not start in my Android emulator. Is it the correct way to write the query? It is showing no errors.
import android.app.Activity;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.*;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class SQLDemo1Activity extends Activity {
private SQLiteDatabase db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
db= SQLiteDatabase.openDatabase(
"/data/data/cis493.sqldatabases/databases/multilinguialdatabase.sqlite",
null,
SQLiteDatabase.CREATE_IF_NECESSARY);
db.beginTransaction();
Cursor cursor = db.query(
"colors" /* table */,
new String[] { "ID" } /* columns */,
"English = ?" /* where or selection */,
new String[] { "green" } /* selectionArgs i.e. value to replace ? */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);
int id = cursor.getInt(0);
TextView met = (TextView) findViewById(R.id.t1);
met.setText(id);
db.endTransaction();
db.close();
}
catch(SQLiteException e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
}
}

You need to put cursor.moveToNext() or cursor.moveToFirst() before trying to get the int with getInt(). Put it in an if statement as there may be no results in the cursor.

To write a query in Android Sqllite requires certain parameters like:
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
URI // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
For more details read Android Developer's Website:
http://developer.android.com/guide/topics/providers/content-provider-basics.html

Related

Searching and retrieving specific data from a previously created SQLite Database in Android?

I have an SQLite Database which I made in SQLite Browser and exported to my Android Application through SQLite Asset Helper Library. This database is for reading-only tasks and can't be upgraded or modified.
Now I want to search in an specific column any data the user input in a TextView, and in case the data matches with some value of the column retrieve all the values corresponding from the other columns.
For example:
TABLE FRUITS
_id NAME URL
1 apple R.drawable.apple
2 orange R.drawable.orange
3 kiwi R.drawable.kiwi
Since my application only allows the user to input the NAME field, the query needs to search in the NAME column only, and retrieve the URL value only if exists in the database, otherwise will return nothing.
Here's my code for importing the database:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "fruitManager";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor answerRequest(String request) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "FRUITS";
qb.setTables(sqlTables);
String[] sqlSelect = {"0 _id", "NAME", "0 URL"};
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
return c;
}
}
And from here I made the request:
public class Request {
private Cursor cursor;
private MyDatabase db;
String request;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite_asset_helper);
public void onClick(View v) {
request = mEdit.getText().toString().toLowerCase();
db = new MyDatabase(this);
cursor = db.answerRequest(request);
url = cursor.getString(c.getColumnIndex("NAME"));
System.out.println("Your request was: " + request +
" and has this URL: " + url);
}
}
protected void onDestroy() {
super.onDestroy();
cursor.close();
db.close();
}
Still, loads of code are needed for do the query but I don't know exactly how to implement them in this case (due to imported database). Thanks in advance.
UPDATE: I'm kinda desperate so if you don't have the answer but know an alternative for do the task (like using another database handler instead of SQLite) I will accept your suggestions as the correct answer.
Only restriction is: Has to be an offline solution (no internet connection needed for access the database).
Your current query looks like this:
`select 0 _id, NAME, 0 URL from FRUITS`
Notice you aren't using the request string anywhere. You are also selecting integer literal 0 and aliasing this to other column names--there doesn't seem to be any reason for this. As is, your results would be
_id NAME URL
0 apple 0
0 orange 0
0 kiwi 0
What you want is the following:
`select * from FRUITS where NAME = request`
Here's how I would write it:
public Cursor answerRequest(String request) {
SQLiteDatabase db = getReadableDatabase();
String table = "FRUITS";
String where = "NAME = ?";
String[] whereArgs = {request};
// select * from fruits where name = request
return db.query(table, null, where, whereArgs, null, null, null);
}
And elsewhere when you want to retrieve the values:
db = new MyDatabase(this);
Cursor cursor = db.answerRequest(request);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
// cursor is not empty, read values here
String url = cursor.getString(cursor.getColumnIndex("URL"));
}
} finally {
cursor.close();
}
}

SQLite database in Android, causes application crash

I'm testing SQLite database in android for the first time.
My program stops as I open it, and i cannot check it, i was wondering if there is a mistake in my code, or database connection,
any help will be appreciated :)
this is my Main.java file:
package de.blattsoft.SQLite;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM MyTable", null);
c.moveToFirst();
Log.d("Ali", c.getString(c.getColumnIndex("FirstName")));
db.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, menu);
return true;
}
}
Note: I have asked this question many times ago, and I have written the full answer of how to implement databases in Android in the answers bellow.
First of all you need to create a database, then insert some data in it an then try to display.
What you are doing is ,if database is not there then create and select the column and display. It will obviously fail and your app crash.
Do something like
public void onCreate(SQLiteDatabase db) {
/*CREATE LOGIN TABLE*/
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT," + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
Then do this ,
public void addMessage(String id, String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, id); //
values.put(KEY_NAME, name);
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
Then you can display ,
You haven't created the database. And inserting or fetching values from the structure which doesn't exist will lead to crash your app. It's like climbing a building which doesn't exist.
So, first create the database then do rest of the things.
For better understanding follow the you tube video tutorial of Slidenerd. They have sequentially explained all the things for beginners here.
Hope it will help.
I have asked this question many times ago when I was an Android noob! :D
right now this is the way I recommend you to use android sqlite database using helper classes.
as an overview, we need to create two classes, DatabaseHelper class
and DataSource class.
What we need to create:
The DatabaseHelper class must extend SQLiteOpenHelper which is a built-in Android class from android.database.sqlite package and its purpose is to manage database creation and version management.
The DataSource class uses our helper class to implement methods which you need for your application.
For Example, we're going to create a database which has one table called users, and the table has 2 columns: id and name;
The id is going to be used as the primary key.
So, let's create the helper class:
DatabaseHelper.java:
package com.mpandg.android.dbtest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
// this tag is used for logging purposes.
public static final String TAG = "database";
// database version.
public static final int DATABASE_VERSION = 1;
// database file name.
public static final String DATABASE_NAME = "database.db";
// table details:
public static final String TABLE_USERS = "users";
public static final String USERS_COLUMN_ID = "id";
public static final String USERS_COLUMN_NAME = "name";
// query of creating users table.
public static final String CREATE_USERS_TABLE =
"CREATE TABLE " + TABLE_USERS + " (" +
USERS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
USERS_COLUMN_NAME + " TEXT" + ")";
// query string of deleting users table.
public static final String DELETE_TABLES =
"DROP TABLE IF EXISTS " + TABLE_USERS + ";";
// constructor method which takes the context and passes it
// to appropriate super method with other database details
// which creates the database.
public DatabaseHelper(Context context) {
// creates the database using given information.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// this line executes the query we made earlier
// to create the users table.
db.execSQL(CREATE_USERS_TABLE);
// log the table creation for debugging.
Log.i(TAG, TABLE_USERS + " has been created.");
}
// whenever you give a new update for your application,
// if you change the version of the database, this method
// will be called, you can do your own complicated operations
// on your tables if you need, but right now, I just delete
// the old table and I make an explicit call to onCreate
// method to create the tables again.
// but never forget that you should never make explicit
// calls to onCreate method, but this is an exception here.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// execute the delete query we made earlier.
db.execSQL(DELETE_TABLES);
// explicit call to onCreate. (read the comment above method)
onCreate(db);
}
}
As you see, we have actually created a subclass of SQLiteOpenHelper and we have implemented onCreate(SQLiteDatabase) and onUpgrade(SQLiteDatabase, int, int) methods, and the helper class we created, takes care of opening the database if it exists, creating it if it does not exist and upgrading it if it's necessary.
Now it's time to use the helper class we created and write our methods to use the database in DataSource class.
We will create a database object and we will instantiate it using the methods in our helper class, and we create methods to insert, select and delete.
So, Let's create DataSource.java:
package com.mpandg.android.dbtest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DataSource {
// create an instance of SQLiteOpenHelper
// but we're going to instantiate it using
// the helper class we created earlier.
SQLiteOpenHelper dbHelper;
// the main database object which will be
// instantiated using the helper class methods.
SQLiteDatabase dataBase;
private final String TAG = "dataSource";
// an string array holding our table's column names
// which is going to be used by database methods.
public static final String[] usersTableColumns = {
DatabaseHelper.USERS_COLUMN_ID,
DatabaseHelper.USERS_COLUMN_NAME
};
// constructor which receives the activity context.
public DataSource(Context context){
// instantiate the dbHelper object using our DatabaseHelper class.
dbHelper = new DatabaseHelper(context);
}
public void open(){
// opening the database or
// creating the table structures for the first time.
// the helper class knows when to open or create the database.
dataBase = dbHelper.getWritableDatabase();
// log the event for debugging purposes.
Log.i(TAG, "database opened");
}
public boolean isOpen () {
// check if the database is already open.
return dataBase.isOpen();
}
public void close(){
// close the database.
dataBase.close();
// log the event for debugging purposes.
Log.i(TAG, "database closed");
}
// insert a name record into database .
public void insertName (String name) {
// ContentValues implements a map interface.
ContentValues values = new ContentValues();
// put the data you want to insert into database.
values.put(DatabaseHelper.USERS_COLUMN_NAME, name);
// passing the string array which we created earlier
// and the contentValues which includes the values
// into the insert method, inserts the values corresponding
// to column names and returns the id of the inserted row.
long insertId = dataBase.insert(DatabaseHelper.TABLE_USERS , null, values);
// log the insert id for debugging purposes.
Log.i(TAG, "added name id:" + insertId);
}
// returns a list of string
// containing the names saved in the database.
public List<String> getNames (){
List<String> names;
// creating the cursor to retrieve data.
// cursor will contain the data when the
// query is executed.
Cursor cursor = dataBase.query(DatabaseHelper.TABLE_USERS, usersTableColumns,
null, null, null, null, null);
// log the number of returned rows for debug.
Log.i(TAG, "returned: " + cursor.getCount() + " name rows .");
// check if the cursor is not null.
if(cursor.getCount()>0){
// instantiate the list.
names = new ArrayList<>();
// cursor starts from -1 index, so we should call
// moveToNext method to iterate over the data it contains.
while (cursor.moveToNext()) {
// read the string in the cursor row using the index which is the column name.
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.USERS_COLUMN_NAME));
// log the retrieved name.
Log.i(TAG, "name retrieved:" + name);
// now add the retrieved name into the list.
names.add(name);
}
// now we have the names in our string list
return names;
} else {
// if the cursor was empty, it means that
// there was no name found in the table,
// so return null.
return null;
}
}
// returns a name corresponding to given id.
public String findNameById (long id){
String name;
// the where clause which is our condition.
String whereClause = DatabaseHelper.USERS_COLUMN_ID + " = ?";
// the arguments passed to
// the where clause. (here is only one argument)
String[] whereArgs = {id+""};
// creating the cursor to retrieve data.
// cursor will contain the data when the
// query is executed.
Cursor cursor = dataBase.query(DatabaseHelper.TABLE_USERS, usersTableColumns,
whereClause, whereArgs, null, null, null);
// log the number of returned rows for debug.
// (logically it should return one row here)
Log.i(TAG, "returned: " + cursor.getCount() + " name rows .");
// check if the cursor is not null.
if(cursor.getCount()>0){
// cursor starts from -1 index, so we should call
// moveToNext method to iterate over the data it contains.
cursor.moveToNext();
// read the string in the cursor row using the index which is the column name.
name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.USERS_COLUMN_NAME));
// log the retrieved name.
Log.i(TAG, "name retrieved:" + name);
return name;
} else {
// if the cursor was empty, it means that
// there was no name found with given id,
// so return null.
return null;
}
}
// delete a name from the table.
public void deleteName (String name) {
// where statement of our delete method.
String whereClause = DatabaseHelper.USERS_COLUMN_NAME + "=" + "?";
// the arguments passed to
// the where clause. (here is only one argument)
String[] whereArgs = {name};
// execute the delete query with delete method.
int deleteId = dataBase.delete(DatabaseHelper.TABLE_USERS , whereClause, whereArgs);
// log the id of the deleted row.
Log.i(TAG, "deleted name id:" + deleteId);
}
}
Now that we have done writing the necessary classes to create and use our database in an appropriate way, it's time to use the methods we wrote in our DataSource class.
All you have to do, is to create an object of DataSource class in your activity and use the methods in it.
when you are intending to use the database, you should open it, you can simply do it by the open() method we wrote in our DataSource class, and after you are done, you must close it to avoid leaks; you can close it using the close() method in 'DataSource` class.
For example, you have some users and you want to add them in the database:
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// insert the names.
dataSource.insertName("Amy");
dataSource.insertName("Johnny");
dataSource.insertName("Abbey");
dataSource.insertName("Miley");
// close the database.
dataSource.close();
Or you want to log all the users in the database:
//TAG for debug logs.
String TAG = "db log";
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// get the names.
List<String> names = dataSource.getNames();
// log all the names in the list.
for (String name: names) {
Log.i(TAG, "retrieved name:" + name);
}
// close the database.
dataSource.close();
Or you want to find a name by its id:
//TAG for debug logs.
String TAG = "db log";
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// find the name by id.
String name = dataSource.findNameById(1);
// log the retrieved name wit id:1.
Log.i(TAG, "retrieved name:" + name);
// close the database.
dataSource.close();
Finally if you want to delete a name:
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// delete the given name
dataSource.deleteName("Amy");
// close the database.
dataSource.close();
That's it.
This is a basic structure for creating databases in Android, as you can see, you can add other tables and columns, easily by adding your own code to the helper class and your own methods to use them in the DataSource class.
Try this
package ir.itstuff.SQLite;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
(EditText) fName = (EditText)findViewById(R.id.editText1);
(EditText) sName = (EditText)findViewById(R.id.editText2);
(Button) save = (Button)findViewById(R.id.button1);
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable(id INTEGER PRIMARY KEY AUTOINCREMENT, FirstName varchar,SecondName varchar);")
//Inserting data from inputs
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String first_name = fName.getText().toString();
String second_name = sName.getText().toString();
String insert_data="INSERT INTO MyTable (FirstName,SecondName) VALUES " + "('" + first_name + "'," + "'" + second_name + "'" + ")";
shoppingListDB.execSQL(insert_data);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
Cursor cr=shoppingListDB.rawQuery("SELECT * FROM MyTable;", null);
if (cr.moveToFirst()){
do{
String name = cr.getString(cr.getColumnIndex("FirstName"));
}
while (cr.moveToNext());
Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show;
}
cr.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, menu);
return true;
}
}

Sqlite column id is not unique

below is my code i just want to display the data i inserted in the sqlite database to a text view but i have this error saying that the id is not unique.
package com.example.sqlitetest;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
TextView scrName, fName;
Button go;
SQLiteDatabase db;
String screenName, fullName;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = openOrCreateDatabase("MyDataBase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE if not exists MyTable(ScreenName Varchar, FullName Varchar, id int(3) PRIMARY KEY);");
db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
cursor = db.rawQuery("Select * from MyTable", null);
cursor.moveToFirst();
scrName = (TextView) findViewById(R.id.scrName);
fName = (TextView) findViewById(R.id.fName);
while(cursor.isAfterLast() == false){
//retrieving the data from sqlite (im not sure if im doing it right)
String screenname = cursor.getString(cursor.getColumnIndex("ScreenName"));
String fullname = cursor.getString(cursor.getColumnIndex("FullName"));
//this are the textview
scrName.setText(screenname);
fName.setText(fullname);
cursor.moveToNext();
}
db.close();
}
}
this is my whole java code. thanks :)
Well I think this project works fine when you run it first time. When you run it second time it gives error because id is your primary key and the row with the id 1 has been already inserted to your database.
To get rid of errors either :
1) uninstall the app and run it again
2) Don't make id as primary key
3) Catch the exception and handle it yourself
Might I suggest an alternative to this. What you can do is make the id column autoincrement as well while still keeping that column as primary key
EDIT:-
Also I have some other suggestions for you:-
db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
you can user ContentValues instead
while(cursor.isAfterLast() == false){
could be replaced with while(!cursor.isAfterLast()){. Looks cleaner this way.
Or you could directly replace while(cursor.isAfterLast() == false){ with while(cursor.moveToNext()){ and can remove out cursor.moveToNext(); from the while block.
Happy Coding!!!

Getting the Relationship contact field on Android

I am working with Androids contacts and trying to get particular pieces of data. I can already get emails, phone numbers, their name, etc. However I am having difficulty getting the relationship field.
http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Relation.html
So my goal is: Given a particular userid (from the contact database on Android), figure out their relation field.
This should work. The idea is to connect search in the Data table but use stuff from CommonDataKinds. This is done in where clause ... Data.MIMETYPE == CommonDataKinds.Relation.CONTENT_ITEM_TYPE. This will get you the row with all the Relation stuff.
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.provider.ContactsContract.Data;
import android.util.Log;
...
public void logCatTheRelation(long contactId){
Uri uri = Data.CONTENT_URI;
String where = String.format(
"%s = ? AND %s = ?",
Data.MIMETYPE,
Relation.CONTACT_ID);
String[] whereParams = new String[] {
Relation.CONTENT_ITEM_TYPE,
Long.toString(contactId),
};
String[] selectColumns = new String[]{
Relation.NAME,
// add additional columns here
};
Cursor relationCursor = this.getContentResolver().query(
uri,
selectColumns,
where,
whereParams,
null);
try{
if (relationCursor.moveToFirst()) {
Log.d("gizm0", relationCursor.getString(
relationCursor.getColumnIndex(Relation.NAME)));
}
Log.d("gizm0", "sadly no relation ... ");
}finally{
relationCursor.close();
}
}

Unable to get phone number from contact list... code inside

Im new to android and programming in general (im a linux sys admin / scripting person). And Ive been trying to get a simple android app going to get a feel for programming but I am having some problems.
I was able to string together some ideas and queries to get a list view of all the contacts, but now id like to be able to grab the phone number of the selected contact but I am not having any luck... I know there is probably better ways to do what I am doing but Im just trying to get a grasp on this.
Code first:
package com.SomeApp;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.database.Cursor;
//import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class CallAppActivity extends ListActivity
{ /** Called when the activity is first created. */
private ListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Get All information from ContactsContract
Cursor managedCursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null
);
//Activity will manage the cursor lifecycle.
startManagingCursor(managedCursor);
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] names = new int[] {R.id.contact_entry};
mAdapter = new SimpleCursorAdapter(
this,
R.layout.main,
managedCursor,
columns,
names
);
setListAdapter(mAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{ super.onListItemClick(l, v, position, id);
Cursor lookup = (Cursor) mAdapter.getItem(position);
String contactId = lookup.getString(
lookup.getColumnIndex(
ContactsContract.Contacts._ID
)
);
Cursor phone_num = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null,
null
);
String phoneId = phone_num.getString(
phone_num.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
)
);
//We are going to print shit to a message box....
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(phoneId);
alertbox.show();
}
}
And now the logcat....
07-23 11:35:34.469: WARN/dalvikvm(781): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-23 11:35:34.479: ERROR/AndroidRuntime(781): FATAL EXCEPTION: main
07-23 11:35:34.479: ERROR/AndroidRuntime(781): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
No matter what Contact I pick I get the same exception, So I obviously am doing something wrong.. I just cant quite figure it out on my own :(
Any help appreciated.
Did you tried to make cursor pointer point to the first row to its data like cursor.moveToFirst() before you access data inside it? Actually, for Cursor phone_num and Cursor phone_id?

Categories

Resources