How to extract phone number from the selected contact? - java

public class ImportContactsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pickContact = (Button) findViewById(R.id.contacts);
pickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
}
});
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1) :
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(People.NAME));
TextView contactView = (TextView) findViewById(R.id.contactView);
contactView.setText(name.toString());
}
}
break;
}
}
I am developing an Android apps and I am importing the phone contacts into my apps, after user clicks on the selected contact, the contact will be shown in a TextView and the phone number will be stored in the sharedpreferences... May I know how to achieve it? Thanks

Have you tried?
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndexOrThrow(People.NAME));
String number = cursor.getString(cursor.getColumnIndexOrThrow(People.NUMBER));
String email = cursor.getString(cursor.getColumnIndexOrThrow(People.PRIMARY_EMAIL_ID));
contactName.setText(name);
contactNumber.setText(number);
contactEmail.setText(email);
For store in SharedPreferences..
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("phonenumber", number);
// Commit the edits!
editor.commit();
The above code is just for understanding..

A possible duplicate of the following link
get contact info from android contact picker
Refer to the above link. It has been answered in detail.

Related

How to pass image gotten from camera or gallery to another activity

1. User selects a button to either upload from gallery or capture from camera
From gallery
choose_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
// Sets the type as image/*. This ensures only components of type image are selected
intent.setType("image/*");
//We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
String[] mimeTypes = {"image/jpeg", "image/png"};
intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
// Launching the Intent
startActivityForResult(intent,1);
}
});
From camera
capture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(UploadActivity2.this, BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
startActivityForResult(intent, 0);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
2. User selects a photo from gallery or capture from camera and the image is displayed in the current activity
public void onActivityResult(int requestCode,int resultCode,Intent data){
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
//Display image with glide
Glide.with(this).asBitmap().load(imgDecodableString).into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<?
super Bitmap> transition) {
display_image.setImageBitmap(resource);
display_image.setVisibility(View.VISIBLE);
}
}
//If request is from camera
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 0:
//Display image in current activity
Glide.with(this)
.load(cameraFilePath)
.into(display_image);
/*display_image.setImageURI(Uri.parse(cameraFilePath));*/
display_image.setVisibility(View.VISIBLE);
break;
}
}
3. I have a 'NEXT' button and when clicked I want to transfer the image displayed (Gotten from either the Gallery or Camera) to another activity, I havn't written a code for passing the image yet
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
startActivity(intent);
}
});
4. I want to know the best way to do this without affecting image quality and memory because in the next activity (UploadAcitivity3), I will be uploading the image passed to the server and saving in a directory
Please follow the steps to achieve this:
Option - 1: If you want to pass multiple images then use below:
Step - 1: Store the selected images path in an ArrayList like below:
private ArrayList<String> selectedImages = new ArrayList<>();
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImages.add(imgDecodableString);
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImages.add(cameraFilePath);
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putStringArrayListExtra("SELECTED_IMAGES", selectedImages);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
ArrayList<String> selectedImages = getIntent().getStringArrayListExtra("SELECTED_IMAGES");
}
Option - 2: If you want to pass single image then use below:
Step - 1: Store the selected image path like below:
private String selectedImage;
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImage = imgDecodableString;
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImage = cameraFilePath;
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("SELECTED_IMAGE", selectedImage);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
String selectedImage = getIntent().getStringExtra("SELECTED_IMAGE");
Glide.with(this).load(selectedImage).into(image_view);
}
You can send the image path through Intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("path", imagePath);
startActivity(intent);
}
});
You already have image path for capturing image is cameraFilePath
and for gallery image imgDecodableString.
Declare String imagePath; as class variable and assign them in onActivityResult.
imagePath = imgDecodableString;//For Gallery
imagePath = cameraFilePath;//For Capture image
Receive path in UploadActivity3.class
String imagePath = getIntent().getStringExtra("path");
Use this path in second activity as you want.

Show selected image in another activity

I've searched on stackoverflow but never found a solution
Here is my situation:
I have a button which start an intent to pick an image
How can I resize proportionally (to keep the aspect ration) and display it on another activity (in imageview)?
I also want to save this resized image to user storage. How can I do that?
Thanks!
Here is my code
MainActivity.java
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, getString(R.string.completeaction)),
PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RequestExternal && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String [] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(MainActivity.this,PhotoResized.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
}
PhotoResized.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoresized);
img = (ImageView) findViewById(R.id.imageView1);
}
For resizing the image use sampling technique provided by dev.android here
Use Lrucache for storing images. Use technique shown here

How to remember bitmap Uri

i'm trying to do an activity which can show picture from gallery. But my Activity needs to remember bitmap uri for another time so it can always open that picture.
here is my .java
edited
i added something else to convert uri to string then string to uri but it doesn't work. Can someone help?
public class DersProgram extends Activity { private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dersprogrami);
Button buttonLoadImage = (Button) findViewById(R.id.button1);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri uri = data.getData();
String BitmapURI;
BitmapURI = uri.toString();
uri = Uri.parse(BitmapURI);
SharedPreferences sharedPreferences = getSharedPreferences("BitmapURI", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("BitmapURI", "your URI as a String").apply();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.resim);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(uri);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
I want to open picture which is called before. Please help me(also i am a beginner) sorry for my English.
As said, use SharedPreferences.
store your bitmapURI as a String in your Activity:
SharedPreferences sharedPreferences = getSharedPreferences("some string", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("BitmapURI", "your URI as a String").apply();
and retrieve it whenever your want:
String bitmapURI = sharedPreferences.getString("BitmapURI", "default string if BitmapURI is not set");

Why is onActivityResult is called before a contact is chosen?

I'm following the answer https://stackoverflow.com/a/867828/129805 to add a contact picker to my app.
The problem is that onActivityResult is immediately invoked with the correct reqCode (PICK_CONTACT), but with aresultCode of 0 and a null for data.
It is not invoked again, when the user actually picks a contact.
The AndroidManifest gives this activity android:launchMode="singleInstance"> as I only ever want there to be one instance.
What have I done wrong?
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
addContactButton = (Button) findViewById(R.id.addContactButton);
addContactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(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) {
Log.d(TAG, "onActivityResult");
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.
Log.d(TAG, "you chose " + name + ".");
}
}
break;
}
}
The singleInstance fires the callback immediately. You have more info in this link

How to receive multiple values using an intent

I have my main activity using the startActivityForResult method which calls an activity that i need to return two string values from. I have it working to return one, but even with all the tutorials and other questions on here i have read i cant seem to get it to return the two values. Below is my code.
here is where i start the second activity:
Button button = (Button) findViewById(R.id.add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
Here is the activity it starts, i need to return the text that is in the titleField(which works now) and the yearField
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.setData(Uri.parse(titleField.getText().toString()));
setResult(RESULT_OK, data);
//data.setData(Uri.parse(yearField.getText().toString()));
//setResult(RESULT_OK, data);
finish();
}
});
}
}
Here is the method in my main class that receives results
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getData().toString();
//tempYear = data.getStringExtra("movieYear");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
The code that is commented out was one attempt at making it receive multiple values, although they failed. Any help with this situation would be great. Thanks!
You should use something like:
Intent returnIntent = new Intent();
returnIntent.putExtra("title",titleField.getText().toString());
returnIntent.putExtra("year",yearField.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
And on your main activity, onActivityResult:
tempTitle = data.getStringExtra("title");
tempYear = data.getStringExtra("year");
use data.putExtra("keys", data); instead of data.setData(.....)
and get data like;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
You should be able be put extras on your intent and get that data through an associated tag. This is how I'm doing it from an Activity's onCreate.
Intent mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("your_tag", "the string you want to get");
startActivity(mIntent);
finish();
Then in the activity you want that data (the MainActivity or whatever you're calling it)....
Intent intent = getIntent();
String value = intent.getExtras().getString("your_tag");
It may also be worth noting that you can Override the onNewIntent in your MainActivity to handle new Intents coming in, mine currently looks like...
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
Try this
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("title_field", titleField.getText().toString);
data.putExtra("year_field", yearField.getText().toString);
setResult(RESULT_OK, data);
finish();
}
});
}
And this
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getStringExtra("title_field");
tempYear = data.getStringExtra("year_field");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
You can use a putExtra method on your Intent:
data.putExtra("title", movieTitle);
data.putExtra("year", movieYear);
Then in the Activity that opens, you can get this data as follows:
String title, year;
Intent data = getIntent();
if (data != null) {
title = data.getExtras().getString("title");
year = data.getExtras().getString("year");
}
You can create a new intent and then add your two variables
Intent i = new Intent(getApplicationContext(), asd8.as.hwapp.timemonday.class);
i.putExtra("username",username);
i.putExtra("password", password);
startActivity(i);
And then retrieving the information in your new activity as so;
public void getInformation(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString("username");
password = extras.getString("password");
}
}

Categories