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

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?

Related

Switching from TextView to ListView in Android

So, I've been following this Vogella ContentProvider tutorial sent to me by a friend, and if you look at the end of section 6.3 you'll see that he says:
If you run this application the data is read from the ContentProvider of the People application and displayed in a TextView. Typically you would display such data in a ListView.
Since I'm new to working with android (and programming in general), I just changed the TextView tag in the main.xml to ListView, and as expected, when I run the app in the emulator, it crashes.
On-demand code:
XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/contactview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Java File:
package de.vogella.android.contentprovider;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
public class ContactsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
TextView contactView = (TextView) findViewById(R.id.contactview);
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactView.append("Name: ");
contactView.append(displayName);
contactView.append("\n");
}
}
private Cursor getContacts() {
// Run query
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);
}
}
I'm sure I'm doing something wrong, can someone point me in the right direction or tell me how to switch it from TextView to ListView?
Also, this is unrelated, but I downloaded the adt bundle and sometimes it doesn't generate the R.java file correctly, it doesn't make any changes to the R.java file and leaves it as the default one that gets generated when you make any new android project, any ideas why?
Note: You don't have to answer this question to get your answer accepted.

Read SMS from a specific number

I want to read a specific SMS in my Inbox. I found on the Internet how to read all the sms in the inbox. That is what I did. Please help me to read just one SMS from a specific number. Thanks
package com.example.liresms;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
public class ReadSMS extends MainActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
String sms = "";
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
}
view.setText(sms);
setContentView(view);
}
}
You're pretty close to already doing it. I suggest you take a look at the arguments for the ContentResolver.query method and pay specific attention to the selection parameter. What you're looking to do is only select messages where a particular column is equal to the number you're looking for...
Something like
Cursor cur = getContentResolver().query(uriSMSURI, null, "from=6159995555", null,null);
I don't know the specific column name off the top of my head, but that should get you started in the right direction...

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();
}
}

Sqlite database query writing

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

Android Contact List

Can anyone shed a light on how to get contact list from android?.
I just want to get the same list as in the dialer app. But im getting a lots of contacts that are not on the dialer list with the code below.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Contacts.People.CONTENT_URI, null, null, null, Contacts.ContactMethods.DEFAULT_SORT_ORDER);
startManagingCursor(cursor);
Thanks in advance.
Try this snippet:
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.SimpleCursorAdapter;
public class ContactList extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, null);
startManagingCursor(cursor);
String[] from = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER};
int[] to = new int[] { R.id.name_entry, R.id.number_entry};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_entry, cursor, from, to);
this.setListAdapter(adapter);
}
}
XML file is:
list_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip">
<TextView
android:id="#+id/name_entry"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center_vertical"
android:textSize="18dip"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/number_entry"
android:singleLine="true"
android:ellipsize="marquee"
android:textSize="18dip"/>
</LinearLayout>
What you have seems fine. Could you elaborate on "getting a lots of contacts that are not on the dialer list"? Is it that Android is making up people? Or is it that you are seeing people with email addresses but no phone numbers (who therefore might not show up in the Dialer)?
Note that Contacts.People is for Android 1.6 and below. That provider is deprecated starting with Android 2.0, replaced by the ContactsContract set of providers.
This is basic implementation of android contact list Activity.
Well, thanks for the answer first. Just to shed a light on this.
I just wanted to get emails only for the contacts on my phone. The "MyContacts" group. I saw this is the group ContactList Activity uses.
I finished doing somethig like this:
c = cr.query(myGroupUri, mEmailsProjection, null, null, null);
....
c.close();
c = cr.query(
Contacts.ContactMethods.CONTENT_URI,
mContactsProjection, contactIds, null, null
);
....
c.close();
Just queried the group first and then the emails table.
try using intent to go to the contact list
startActivityForResult( new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI),1);}

Categories

Resources