**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;
}
}
Related
I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the checkbox.But the data doesn't get transferred. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
}
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artist.sender/com.example.artist.sender.contacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
This is the logcat for the error. It keeps showing that the setitemOnClickListener keeps referring to a null object whereas, I've already assigned the listview to its respective id.
EDIT:**I've fixed part of the error, by renaming the setContentView(R.layout.activity_main); in the contacts class to setContentView(R.layout.contacts); But now after that, it shows this error, **java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
If the data in the database, or some other storage, only pass the _id or the location, respectively.
Instead of passing many extras, Android way is, actually, Parcable. Here a nice tutorial from Vogella
public class TestModel implements Parcelable {
String name;
String phoneNumber;
//.....
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.phoneNumber);
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
#Override
public TestModel createFromParcel(Parcel source) {
return new TestModel(source);
}
#Override
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
}
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() + " ");
}
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.
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;
}
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..