How to save Array of phone number into SharedPreference - android

I want to save phone number using SharedPreference . As it has been fetched from phone book and set in textView i am unable to save every one of them in SharedPreference. Please help me towards how to save and retrive set of phone number(array or set) via SharedPreference and send it to another fragment for messaging the number.
Contact.java
package com.kamal.sos10;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.Tag;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Contact extends AppCompatActivity {
EditText msg,editText2,editText3,editText4;
Button con1,con2,con3;
TextView textView3,textView5,textView6,textView7,textView8,textView9;
TextView text1;
// static final int PICK_CONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
msg=(EditText)findViewById(R.id.msg);
// editText2=(EditText)findViewById(R.id.editText2);
textView3=(TextView)findViewById(R.id.textView3);
// text1=(TextView)findViewById(R.id.first);
textView5=(TextView)findViewById(R.id.textView5);
textView6=(TextView)findViewById(R.id.textView6);
textView7=(TextView)findViewById(R.id.textView7);
textView8=(TextView)findViewById(R.id.textView8);
textView9=(TextView)findViewById(R.id.textView9);
con1=(Button)findViewById(R.id.con1);
con2=(Button)findViewById(R.id.con2);
con3=(Button)findViewById(R.id.con3);
con1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text1", "1");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 1);
}
}
});
con2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text2", "2");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent,2);
}
}
});
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text3", "3");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 3);
}
}
});
int num = Integer.valueOf(textView3.getText().toString());
int num2 = Integer.valueOf(textView6.getText().toString());
int num3 = Integer.valueOf(textView7.getText().toString());
Integer[] array=new Integer[3];
array[0]=num;
array[1]=num;
array[2]=num;
for (int j=0;j<3;j++)
{
Log.i("key", String.valueOf(array[j]));
}
/*
SharedPreferences sharedPreferences=this.getSharedPreferences("com.kamal.sos10", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putInt("array_size", strings.length);
for(int i=0;i<strings.length; i++)
edit.putString("array_" + i, strings[i]);
edit.commit();
int size = sharedPreferences.getInt("array_size", 0);
strings = new String[size];
for(int i=0; i<size; i++) {
strings[i]= sharedPreferences.getString("array_" + i, null);
Log.i("sdert",strings[i]);
}
*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 || requestCode == 2 || requestCode == 3) {
if (resultCode == this.RESULT_OK) {
contactPicked(data,requestCode);
}
}
}
private void contactPicked(Intent data,int req) {
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cur = this.getContentResolver().query(uri, null, null, null, null);
cur.moveToFirst();
// column index of the contact ID
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// column index of the contact name
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// column index of the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
String text1 = getIntent().getStringExtra("extra_text1");
Toast.makeText(Contact.this, text1, Toast.LENGTH_SHORT).show();
if (req==1)
{
textView3.setText(phone);
Toast.makeText(Contact.this, textView3.getText(), Toast.LENGTH_SHORT).show();
int num = Integer.valueOf(textView3.getText().toString());
Log.i("yut", String.valueOf(num));
textView5.setText(name);
}
if (req==2)
{
textView6.setText(phone);
textView8.setText(name);
}
if (req==3)
{
textView7.setText(phone);
textView9.setText(name);
}
pCur.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}

You can save ArrayList/Array/List to SharedPrefernces Here is How you can do it
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
but You an refer this link for details and this link . these Are useful and easy to understand.
For your second part To Send the Data to Fragment
Well I would suggest to save the data in the current Activity/Fragment what ever you have and then get the data from shared preferences in the fragment you wish to open but in case if you really want to get the data and to send the data to the fragment consider this link please.
Note:
By Looking at your code I think there could be large amount of contacts, so it means that you will have a large array. I will suggest you to store them in database as you can easily retrieve/update/delete any data and record.
Update : (after getting clear in comments )
You have written the code to get the contacts from the Textview in On create where as I think the contacts in textviews gets update later where as that code in the onCreate run before it.
make this change
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Just check it here
int num = Integer.valueOf(textView3.getText().toString());
int num2 = Integer.valueOf(textView6.getText().toString());
int num3 = Integer.valueOf(textView7.getText().toString());
Integer[] array=new Integer[3];
array[0]=num;
array[1]=num;
array[2]=num;
for (int j=0;j<3;j++)
{
Log.i("key", String.valueOf(array[j]));
}
}
});

after api level 11 Set will be stored in preferences so convert your Array or List to set and stored in preferences
Set<String> setNameYouWantToStore = new HashSet<String>();
setNameYouWantToStore.addAll(listOfDetails);
scoreEditor.putStringSet("keyForSet", setNameYouWantToStore);
scoreEditor.commit();
For Retriving using Iterator
Set<String> setNameYouWantToStore = new HashSet<String>();
Iterator iterator = setNameYouWantToStore.iterator();
while(iterator.hasNext()) {
System.out.println("Value: " + iterator.next() + " ");
}

Related

Android: Unable to return number from startActivityForResult

I am trying to write an app that has two buttons - the first brings up a list of contacts and the second sends a message to the selected contact. I am able to select a contact using startActivityForResult and onActivityResult, but I cannot return the contact's number to my main code where it would be read by the second button's onClick method. When running the code below, I get the toast message with the phone number but when I try to send a message I get the "Please select a contact first" message. I don't know how to make the "phoneNumber" variable in onActivityResult to send it to "phoneNumber" in my main activity. Thanks!
package com.example.testa;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidAlarmService extends Activity {
private PendingIntent pendingIntent;
private static final int PICK_CONTACT_REQUEST = 0;
private static final Uri CONTACTS_CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
static String phoneNumber = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button contacts_button = (Button) findViewById(R.id.getContacts);
contacts_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, CONTACTS_CONTENT_URI);
intent.setType(Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
} catch (Exception e) {
Log.e("AAS", "Found an error in contacts button");
}
}
});
final Button send_button = (Button) findViewById(R.id.send_button);
send_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
final String yourtext = "my message";
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
if (phoneNumber == ""){
Toast.makeText(AndroidAlarmService.this, "Please select a contact first" , Toast.LENGTH_SHORT).show();
//This is the message I get
return;
}
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("yourtext", yourtext);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
//this part is working
}
}
Change
String number = c.getString(0);
to
phoneNumber = c.getString(0);
This will store the phone number in the member variable rather than in a local variable. Now you can use this phoneNumber member variable in the click listener for your second button.
Note that phoneNumber == "" is an error. You should use equals() to compare String instances for equality.

how can i add only unique contact in my list in android

all..i have made a demo in android in that i have opened intent of addressbook and in my "onActivityResult" i am binding Contact name to List,All is going well but problem is i want ,if 1 contact name isalready added it shouldnt be added again ,my code is as below:
main.java
package com.example.mycontactpicker;
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public Button add;
public TextView contact;
public LinearLayout list;
private static final int CONTACT_PICKER_RESULT = 1200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.add);
list = (LinearLayout) findViewById(R.id.list);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
String orgName = "";
String title = "";
String emailId = "";
String cNumber = "";
String zipCode = "";
if (c.moveToFirst()) {
// Fetch Contact Name
String DisplayName = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("==============Display name:::::::::;; "
+ DisplayName);
View inflateView;
inflateView = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.contact_row, null, true);
contact = (TextView) inflateView.findViewById(R.id.contact);
contact.setText(DisplayName);
list.addView(inflateView);
Toast.makeText(getApplicationContext(), DisplayName,
Toast.LENGTH_LONG).show();
String hasPhone = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String contactId = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
// long id = c.getLong(Integer.parseInt(contactId));
if (DisplayName.equals("") || DisplayName.equals(" ")) {
DisplayName = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE));
System.out
.println("=============Display name:::::::::::outer side "
+ DisplayName);
}
}
}
}
}
}
pls help frends
To check if a contact name already exists in the address book you could add...
public boolean contactExists(String contact) {
if (contact != null) {
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
if (contact.equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)))) {
return true;
}
}
}
return false;
}

how to close contact list after pick (android)

**im trying to do n sms app and im using this code to pick some data from contact my
probleam is when im closing my app the contact list is still opend.. how can i close it?
is there any way to pick the data and force close the contact list activity?
**
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnTouchListener{
TextView a1,a2;
EditText contact,message;
Button send;
String name,phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initilaize();
}
public void initilaize(){
a1 = (TextView)findViewById(R.id.tVContact);
a2 = (TextView)findViewById(R.id.tVMessage);
contact = (EditText)findViewById(R.id.eTContact);
message = (EditText)findViewById(R.id.eTMessage);
send = (Button)findViewById(R.id.button1);
name ="";
phoneNumber="";
contact.setOnTouchListener(this);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri contactData = data.getData();
try {
String id = contactData.getLastPathSegment();
Cursor phoneCur = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
final ArrayList<String> phonesList = new ArrayList<String>();
while (phoneCur.moveToNext()) {
// This would allow you get several phone addresses
// if the phone addresses were stored in an array
String phone = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phonesList.add(phone);
}
phoneCur.close();
//
String name="";
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
c.close();
//
if (phonesList.size() == 0) {
} else{
phoneNumber = phonesList.get(0);
this.name = name;
contact.setText(name);
} } catch (Exception e) {
Log.e("FILES", "Failed to get phone data", e);
}
}
}
}
public boolean onTouch1(View v, MotionEvent arg1) {
switch(v.getId()){
case R.id.eTContact:{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent,0);
break;
}
case R.id.button1:{
}
}
return true;
}
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}

My edittext not showing the callLog numbers when pressed eventhough i am able to get into callLog

After some research and coding, I am able to get into my callLog. after i added more codes so that I am able to retrieve the numbers from callLog to my edittext, there seem to be errors. I have googled on this but so far to no avail. Any advise? -Simon-
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SimonCallLogActivity extends Activity {
/** Called when the activity is first created. */
EditText display;
Button log;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//to go to Call Log//
log=(Button)findViewById(R.id.button1);
log.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent myIntent=new Intent();
myIntent.setAction(Intent.ACTION_CALL_BUTTON);
startActivity(myIntent);
}
});
}
//Call Log//
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final EditText number = (EditText) findViewById(R.id.editText1);
Cursor cursor = null;
String phoneNo = " ";
List<String> logNumbers = new ArrayList<String>();
String[] projection = new String[] {CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.CACHED_NAME};
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection, null, null, CallLog.Calls.DATE + " ASC");
getColumnData(managedCursor);
}
private void getColumnData(Cursor cur){
try{
if (cur.moveToFirst()) {
String name;
String number;
long date;
int nameColumn = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int numberColumn = cur.getColumnIndex(CallLog.Calls.NUMBER);
int dateColumn = cur.getColumnIndex(CallLog.Calls.DATE);
System.out.println("Reading Call Details: ");
do {
name = cur.getString(nameColumn);
number = cur.getString(numberColumn);
date = cur.getLong(dateColumn);
System.out.println(number + ":"+ new Date(date) +":"+name);
// number.setText(numberColumn);
} while (cur.moveToNext());
}
}
finally
{
cur.close();
}
final String [] items = logNumbers.toArray(new String[logNumbers.size() ]) ;
AlertDialog.Builder builder = new AlertDialog.Builder(SimonCallLogActivity.this);
builder.setTitle("Choose a number: ");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
String selectedNumber = items[item].toString();
selectedNumber= selectedNumber.replace("-","");
selectedNumber= selectedNumber.replace("Home:", "");
selectedNumber= selectedNumber.replace("Mobile:", "");
selectedNumber= selectedNumber.replace("Work:", "");
selectedNumber= selectedNumber.replace("Other:", "");
//selectedNumber = selectedNumber.replace("+","");
number.setText(selectedNumber);
}
});
AlertDialog alert = builder.create();
if(logNumbers.size()>1){
alert.show();
}else{
String selectedNumber= phoneNo.toString();
selectedNumber=selectedNumber.replace("-", "");
number.setText(selectedNumber);
}
if(phoneNo.length()==0){
Log.d("SIMON", "No contact");
}
}
break;
}
}else
{
//gracefully handle failure
Log.w("SIMON","Warning activity not okay");
}
}
}
Declare logNumbers and number as members of your SimonCallLogActivity class.
public class SimonCallLogActivity extends Activity {
/** Member variables */
EditText display;
Button log;
List<String> logNumbers = new ArrayList<String>();
EditText number;
...
...
}
Remove their local declarations..

How to call Android contacts list?

I'm making an Android app, and need to call the phone's contact list. I need to call the contacts list function, pick a contact, then return to my app with the contact's name. Here's the code I got on the internet, but it doesnt work.
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class Contacts extends ListActivity {
private ListAdapter mAdapter;
public TextView pbContact;
public static String PBCONTACT;
public static final int ACTIVITY_EDIT=1;
private static final int ACTIVITY_CREATE=0;
// Called when the activity is first created.
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Cursor C = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(C);
String[] columns = new String[] {People.NAME};
int[] names = new int[] {R.id.row_entry};
mAdapter = new SimpleCursorAdapter(this, R.layout.mycontacts, C, columns, names);
setListAdapter(mAdapter);
} // end onCreate()
// Called when contact is pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor C = (Cursor) mAdapter.getItem(position);
PBCONTACT = C.getString(C.getColumnIndex(People.NAME));
// RHS 05/06
//pbContact = (TextView) findViewById(R.id.myContact);
//pbContact.setText(new StringBuilder().append("b"));
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
}
I'm not 100% sure what your sample code is supposed to do, but the following snippet should help you 'call the contacts list function, pick a contact, then return to [your] app with the contact's name'.
There are three steps to this process.
1. Permissions
Add a permission to read contacts data to your application manifest.
<uses-permission android:name="android.permission.READ_CONTACTS"/>
2. Calling the Contact Picker
Within your Activity, create an Intent that asks the system to find an Activity that can perform a PICK action from the items in the Contacts URI.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Call startActivityForResult, passing in this Intent (and a request code integer, PICK_CONTACT in this example). This will cause Android to launch an Activity that's registered to support ACTION_PICK on the People.CONTENT_URI, then return to this Activity when the selection is made (or canceled).
startActivityForResult(intent, PICK_CONTACT);
3. Listening for the Result
Also in your Activity, override the onActivityResult method to listen for the return from the 'select a contact' Activity you launched in step 2. You should check that the returned request code matches the value you're expecting, and that the result code is RESULT_OK.
You can get the URI of the selected contact by calling getData() on the data Intent parameter. To get the name of the selected contact you need to use that URI to create a new query and extract the name from the returned cursor.
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}
Full source code: tutorials-android.blogspot.com (how to call android contacts list).
I do it this way for Android 2.2 Froyo release:
basically use eclipse to create a class like:
public class SomePickContactName extends Activity
then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);
}//onCreate
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
getContactInfo(intent);
// Your class variables now have the data, so do something with it.
}
}//onActivityResult
protected void getContactInfo(Intent intent)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}//getContactInfo
Looking around for an API Level 5 solution using ContactsContract API you could slightly modify the code above with the following:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
And then in onActivityResult use the column name:
ContactsContract.Contacts.DISPLAY_NAME
Here is the code snippet for get contact:
package com.contact;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GetContactDemoActivity extends Activity implements OnClickListener {
private Button btn = null;
private TextView txt = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
txt = (TextView) findViewById(R.id.textView1);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
if (arg0 == btn) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
} catch (Exception e) {
e.printStackTrace();
Log.e("Error in intent : ", e.toString());
}
}
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Log.e("Phone no & name :***: ", name + " : " + no);
txt.append(name + " : " + no + "\n");
id = null;
name = null;
no = null;
phoneCur = null;
}
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgumentException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}
}
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT && intent != null) //here check whether intent is null R not
{
}
}
because without selecting any contact it will give an exception. so better to check this condition.
The complete code is given below
package com.testingContect;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Contacts.People;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class testingContect extends Activity implements OnClickListener{
/** Called when the activity is first created. */
EditText ed;
Button bt;
int PICK_CONTACT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt=(Button)findViewById(R.id.button1);
ed =(EditText)findViewById(R.id.editText1);
ed.setOnClickListener(this);
bt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
break;
case R.id.editText1:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(this, "Contect LIST = "+name, Toast.LENGTH_LONG).show();
}
}//onActivityResult
}//class ends
Be careful while working with the android contact list.
Reading the contact list in the above methods works on most android devices except HTC One and Sony Xperia. It wasted my six weeks trying to figure out what is wrong!
Most tutorials available online are almost similar - first read "ALL" contacts, then show in Listview with ArrayAdapter. This is not memory efficient solution. Instead of looking for solutions on other websites first, have a look at developer.android.com. If any solution is not available on developer.android.com you should look somewhere else.
The solution is to use CursorAdapter instead of ArrayAdapter for retrieving the contact list. Using ArrayAdapter would work on most devices, but it's not efficient. The CursorAdapter retrieves only a portion of the contact list at run time while the ListView is being scrolled.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
// Gets the ListView from the View list of the parent activity
mContactsList =
(ListView) getActivity().findViewById(R.layout.contact_list_view);
// Gets a CursorAdapter
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contact_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
}
Retrieving a List of Contacts: Retrieving a List of Contacts
To my surprise, you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time).
However, you do need permission to read the details of the contact like the phone number.
I am using this method to read Contacts
public static List<ContactItem> readPhoneContacts(Context context) {
List<ContactItem> contactItems = new ArrayList<ContactItem>();
try {
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
/*context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
new String[] { id },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");*/
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
ContactItem contactItem = new ContactItem();
contactItem.setContactName(contactName);
//the below cursor will give you details for multiple contacts
Cursor pCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
//Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
switch (phoneType) {
case Phone.TYPE_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case Phone.TYPE_OTHER:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
contactItem.setSelectedAddress(getContactPostalAddress(pCursor));
pCursor.close();
contactItems.add(contactItem);
}
}
cursor.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return contactItems;
}//loadContacts
I have a code to save the contact in your database by shared preference
here is my code
public class MainActivity extends AppCompatActivity {
EditText nameInput,phoneInput;
TextView LargeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
nameInput = (EditText) findViewById(R.id.nameInput);
phoneInput = (EditText) findViewById(R.id.phoneInput);
LargeText = (TextView) findViewById(R.id.textView2);
}
public void saveInfo (View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString("name", nameInput.getText().toString());
editor.putString("phone", phoneInput.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void displayData(View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
String ph = sharedPref.getString ("phone","");
LargeText.setText(name + " " + ph);
}
}
-> Add a permission to read contacts data to your application manifest.
<uses-permission android:name="android.permission.READ_CONTACTS"/>
-> Use Intent.Action_Pick in your Activity like below
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
-> Then Override the onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
Uri uri = data.getData();
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
phoneNo = cursor.getString(phoneIndex);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
This will work check it out
I use the code provided by #Colin MacKenzie - III. Thanks a lot!
For someone who are looking for a replacement of 'deprecated' managedQuery:
1st, assuming using v4 support lib:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
2nd:
your_(activity)_class implements LoaderManager.LoaderCallbacks<Cursor>
3rd,
// temporarily store the 'data.getData()' from onActivityResult
private Uri tmp_url;
4th, override callbacks:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// create the loader here!
CursorLoader cursorLoader = new CursorLoader(this, tmp_url, null, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
getContactInfo(cursor); // here it is!
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
5th:
public void initLoader(Uri data){
// will be used in onCreateLoader callback
this.tmp_url = data;
// 'this' is an Activity instance, implementing those callbacks
this.getSupportLoaderManager().initLoader(0, null, this);
}
6th, the code above, except that I change the signature param from Intent to Cursor:
protected void getContactInfo(Cursor cursor)
{
// Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
// same above ...
}
7th, call initLoader:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (PICK_CONTACT == requestCode) {
this.initLoader(data.getData(), this);
}
}
8th, don't forget this piece of code
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
this.act.startActivityForResult(intentContact, PICK_CONTACT);
References:
Android Fundamentals: Properly Loading Data
Initializing a Loader in an Activity

Categories

Resources