I develop an app in android and I want when to press a button opens the contacts and choose one name and fill that name in EditText .. just like the SMS message.
here my code it just open the contact and when I choose the name it's going nowhere!
addto.setOnClickListener(new View.OnClickListener() {
private static final int PICK_CONTACT = 0;
#Override
public void onClick(View v) {
Intent it= new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(it, PICK_CONTACT);
}
});
You can get contact information in onActivityResult() method inside your activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PICK_CONTACT:
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
//Get number and name from cursor
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//set number and name in editext
etName.setText(contactName);
etNumber.setText(number);
break;
}
}
}
Related
I have an app that opens up a file picker and it outputs the path of that file in a Toast Message.
But I would like to change it such that the file that I pick is passed as a parameter to a function.
My activity looks like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_picker);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
break;
}
}
}
And it does what it is supposed to do but instead of outputting the file path, I would like to call the function
importToFile()
From the manage class.
I would like to do something like this:
manage.importToFile(File1)
Where File1 is the file I selected from the file picker.
How can I do that.
Thanks in advance.
You can use File class in android to work with files. Create an instance of File using the path of the selected file and pass it to that method of yours. Something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
// as #Taseer Ahmad said its not a good way to get path of the file.
//String PathHolder = data.getData().getPath();
String PathHolder = getPath(this, data.getData());
if (!TextUtils.isEmpty(PathHolder)) {
File file = new File(PathHolder);
manager.importToFile(file);
Toast.makeText(MainActivity.this, "The Files path is: "+ PathHolder, Toast.LENGTH_LONG).show();
}
}
break;
}
}
EDIT
As #Taseer Ahmad said, data.getData().getPath() is not a safe way to get path of the selected file. This code is copied from here.
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}
I am having problems with a global variable in my Java code. Here is the thing: My Screen has 3 ImageButtons elements for picking 3 images when pressing on them; this works fine. I am using onActiviyResult in order to make it, but I have implemented just one onActiviyResult method for the 3 images, so I am using 3 if(){...} blocks in the method to know the pressed imagebutton, I mean this:
if(current_picture.equals("pic1"))}{
imagebutton1.setImageBitmap(bitmap);
}
if(current_picture.equals("pic2"))}{
imagebutton2.setImageBitmap(bitmap);
}
if(current_picture.equals("pic3"))}{
imagebutton3.setImageBitmap(bitmap);
}
Here, current_picture is a String, and it's declared outside the onCreate method, and its default value is set to: String current_picture = "";
I use this variable to save a value that was set on the setonclicklistener events of the 3 imagebuttons, I mean:
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic1";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
Same thing for imagebutton2 (current_picture = "pic2";) and imagebutton3 (current_picture = "pic3";). All these events are on onCreate method obviously.
So, the problem is that current_picture is losing its value set on the setonclicklistener methods when calling onActivityResult method, I mean, current_user value is still "" and not "pic1", "pic2" or "pic3" depending on the pressed imagebutton. I think its value is destroyed when calling the new activity onActivityResult, then onActivityResul just recognizes: String current_picture = "";
I have done many things to solve this but i am able to find a solution, I attached some code (not all, just important parts) below:
public class Publish_Event extends Activity{
private ImageButton imagebutton1;
private ImageButton imagebutton2;
private ImageButton imagebutton3;
private Bitmap bitmap;
private String current_picture="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.publicar_eventos);
StrictMode.ThreadPolicy p = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(p);
imagebutton1 = (ImageButton)findViewById(R.id.pic1);
imagebutton2 = (ImageButton)findViewById(R.id.pic2);
imagebutton3 = (ImageButton)findViewById(R.id.pic3);
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic1";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
imagebutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic2";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
imagebutton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic3";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
imagen_path = getRealPathFromURI(selectedImageUri);
bitmap = BitmapFactory.decodeFile(imagen_path);
if(current_picture.equals("pic1")){
imagebutton1.setImageBitmap(bitmap);
}
if(current_picture.equals("pic2")){
imagebutton2.setImageBitmap(bitmap);
}
if(current_picture.equals("pic3")){
imagebutton3.setImageBitmap(bitmap);
}
}
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public String getRealPathFromURI(Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = Publish_Event.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor =
Publish_Event.this.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
String path = null;
try {
int column_index =
cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}
}
You can start activity with different request code.
public class Publish_Event extends Activity{
private static final int SELECT_PICTURE_1 = 1;
private static final int SELECT_PICTURE_2 = 2;
private static final int SELECT_PICTURE_3 = 3;
protected void onCreate(Bundle savedInstanceState) {
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a picture"), SELECT_PICTURE_1);
}
});
imagebutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a picture"), SELECT_PICTURE_2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE_1) {
//change imagebutton1
}else if(requestCode == SELECT_PICTURE_2){
//change imagebutton2
}else if(requestCode == SELECT_PICTURE_3){
//change imagebutton3
}
}
}
}
I'm trying to get a contacts name from my contacts by using an Intent, it seems the method I found earlier is deprecated and when I try to use it my app force quits. I'm new to Android development and any help would be appreciated.
public void openContacts(View view) {
Intent contactsIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactsIntent, 1);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if(c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(Contacts.People.NAME));
TextView contactName = (TextView)findViewById(R.id.contact_name_textview);
contactName.setText(name);
}
}
}
}
I'm calling the openContacts function as an onClick event for a button. Once I've picked my contact I would like to set the name to a TextView that I have already made.
btngal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(Intent.ACTION_PICK,android.provider.ContactsContract.Contacts.CONTENT_GROUP_URI);
startActivityForResult(i,0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
if (requestCode == 0) {
Uri selectContact=data.getData();
String[] filePathColumn={Contacts.CONTENT_URI.toString()};
Cursor cursor = getContentResolver().query(selectContact,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
}
}
}
While doing this action I am getting below error:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.PICK dat=content://com.android.contacts/contacts/group }
In order to read contacts from native android app, you need permission, like this in your manifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Make sure you have that one.