Use a TextView to get a Contact from Address Book - java

I'm very new to Android Dev and am having issues trying to get an editText to pull out one contact. I've created 3 editTexts that will take a contact each and will send a SMS to the selected contact(s).
http://imgur.com/IbAT1hX
I've tried several things that I've found online, but they all crash and I don't really understand what I'm doing.
I know that I have to create a onClickListener():
contact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
The other question that I have is, since I need to select one contact per EditText, do I have to copy the same code for the three EditTexts?
After the contact is selected I would like to display just the name of the contact.
Any help would be appreciated!

You can do like i did in one of my app (I did this on button click you and use your edittext)
Open The contact
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
Then after user select you can get the result in OnActivityResult Method and process the contact uri to load details of contact
#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 = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Fetch other Contact details as you want to use
Set the name of contact in your editText
}
}
break;
}
}

Related

Need help on how to use onActivityResult() on Adapter Class?

I tried to return a phone number from a contact list on my adapter class, when i use super.onActivityResult(requestCode, resultCode, data); I got error.
btnContactGift.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// Show only contacts with phone numbers
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
// Start the Contacts activity
context.startActivityForResult(intent, PICK_CONTACT);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_CONTACT :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = conR.query(contactData, projection, null, null, null);
c.moveToFirst();
int nameIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
String name = c.getString(nameIdx);
String phoneNumber = c.getString(phoneNumberIdx);
String photo = c.getString(photoIdx);
if (name == null) {
name = "No Name";
}
String nwPhone = phoneNumber.replace("+251", "0");
edtPhoneGift.setText(nwPhone);
c.close();
// Now you have the phone number
}
break;
}
}
Can not resolve method onActivityResult(int, int, Intent)
onActivityResult() needs to be implemented on the activity or fragment on which you call startActivityForResult(). In your case, that would be whatever activity or fragment is identified by context (from context.startActivityForResult(intent, PICK_CONTACT)).
Just delete the call to super super.onActivityResult(requestCode, resultCode, data), you don't need that.
Also, you need to change the ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI in your projection to something else, you can get Photo.XXX fields from the Uri returned from a Phone Picker intent, only columns within Phone.XXX or implicitly joined to it, you can try using Contacts.PHOTO_ID instead.

Passing bundle instance to place picker intent

I am working on an android app whose main purpose is to update the working location of the employees by admin. Now when I want to change/update the location of an employee from my recycler view(list of employees connected with my UserManagerAdapter), I have to pass the user name of that employee to the place picker intent so that when the admin pick the desired location, the database of that user will be changed accordingly.
My Steps(2 Steps)
I have passed the username to the place picker intent as bundle.
My UserManagerAdapter
holder.locationTv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchPicker(data.get(position).getUserName());
}
});
private void launchPicker(String userName) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Bundle bundle = new Bundle();
bundle.putString(USERNAME,userName);
try {
fragment.startActivityForResult(builder.build(fragment.getActivity()),PLACE_PICKER_REQUEST,bundle);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
I received the location request inside of a fragment and update the location of that particular user
My ManageUserFragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PLACE_PICKER_REQUEST){
if(resultCode == RESULT_OK){
Place place = PlacePicker.getPlace(getContext(),data);
address = place.getAddress().toString();
String latLng = place.getLatLng().toString();
latLang = latLng;
//update user's decided location
Bundle bundle = data.getExtras();
String userName = bundle.getString(USERNAME);// it returns null, Why?
updateLocation(latLang,userName);
Toast.makeText(getContext(), latLng, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), getContext().getText(R.string.locationError), Toast.LENGTH_SHORT).show();
}
}
}
My constant is
public static final String USERNAME="Username";
Now,
My problem is
Why bundle.getString(USERNAME) always return null?
How to pass data to place picker intent so that we can receive it in
onActivityResult ?
After replicating your case and researching for a little bit, I found out that the third parameter in startActivityForResult() is not used to pass a bundle of values to the onActivityResult, it's used to pass options to Android itself, you can find those here. So if you want to pass any data you have to use an intent with putExtra("USERNAME", username), and you can retrieve it with getStringExtra("USERNAME"). It's explained in this answer as well.

How to read results from startActivityForResults

Team
My question is, how do I read the result from the startAtcivityForResult.
When the button is pressed, it calls bStock(), which makes a URL call and retrieves data. I have verified the URL call is correct and that I do get data.
I have used finishActivity(1) to not display the actual content or result. For the sake of this message here is what I get when not using finishActivity(1)
My goal is to read the result and only display certain values like name and last price. Here is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.content_layout_id);
final Button buttonStock = findViewById(R.id.buttonS);
buttonStock.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bStock();
}
});
}
static final int REQUEST_CODE = 1;
protected void bStock() {
String url = "http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=AG";
Uri uri = Uri.parse(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
i.setPackage("com.android.chrome");
startActivityForResult(i, REQUEST_CODE);
finishActivity(1);
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
// Make sure the request was successful
//if (resultCode == RESULT_OK) { // 0 -1
// Get the URI that points to the selected contact
Uri o = data.getData();
Toast.makeText(MainActivity.this, "Name ", Toast.LENGTH_LONG).show();});
}
}
I am using a Toast (for now) just to display the name, but I do not know how to read data. Any help would be appreciated.
Jesse
That does not work as you expect, because the activity you are trying to start (chrome browser) is not prepared to return the result you want, to you. The intent (VIEW) tells the browser, to do just that -- view the given URL.
For activities that are not your own, you have to carecully check their description to see if they support any calls for results, and how they return it -- e.g. there is a 'take a picture' intent, that will return the picture taken to you via some uri data.
Most of the time, startActivityForResult is used to start your own activities, which you want to return data to the calling activity. In that case, you can define yourself, on how to pass the results back to the calling activity.
you may need to iterate through a cursor
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}

Android: cannot get values using .getStringExtra

I'll just go straight to the problem. In UploadNotesActivity.java....
First, I pick a .pdf file using intent
chooseNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// Start the Intent
startActivityForResult(intent, RESULT_LOAD_FILE);
}
});
and then, in `onActivityResult, I save the filePath of the picked file.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK && data != null) {
data.putExtra("filePath", data.getData().getPath());
choosenFile.setText(data.getStringExtra("filePath"));
} else {
Toast.makeText(this, "Error in choosing file",
Toast.LENGTH_LONG).show();
}
}
click Upload button to start upload the file
uploadNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onUploadButtonClick();
}
});
the onUploadButtonClick()
private void onUploadButtonClick() {
final String serverUrlString = "http://XXXX/uploadNotes.php";
if (getIntent().getStringExtra("filePath").isEmpty()) {
Log.d(TAG, "filePath is null");
} else {
Log.d(TAG, getIntent().getStringExtra("filePath"));
}
final String fileToUploadPath = getIntent().getStringExtra("filePath");
final String paramNameString = "uploaded_file";
String fileName[] = fileToUploadPath.split("/");
final MultipartUploadRequest request =
new MultipartUploadRequest(this, UUID.randomUUID().toString(), serverUrlString);
request.addFileToUpload(fileToUploadPath, paramNameString,
fileName[fileName.length-1]+".pdf", ContentType.APPLICATION_OCTET_STREAM);
request.setNotificationConfig(R.drawable.ic_launcher,
getString(R.string.app_name),
getString(R.string.uploading),
getString(R.string.upload_success),
getString(R.string.upload_error),
false);
// if you comment the following line, the system default user-agent will be used
request.setCustomUserAgent("UploadServiceDemo/1.0");
// set the intent to perform when the user taps on the upload notification.
// currently tested only with intents that launches an activity
// if you comment this line, no action will be performed when the user taps
// on the notification
// request.setNotificationClickIntent(new Intent(this, MainActivity.class));
// set the maximum number of automatic upload retries on error
request.setMaxRetries(2);
try {
request.startUpload();
} catch (Exception exc) {
Toast toast = Toast.makeText(getApplicationContext(), "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_LONG);
toast.show();
}
}
But the problem is, it will throw null pointer exception, which I don't quite get the reason.
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.onUploadButtonClick(UploadNotesActivity.java:73)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.access$100(UploadNotesActivity.java:19)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity$2.onClick(UploadNotesActivity.java:53)
line 73: if (getIntent().getStringExtra("filePath").isEmpty())
line 19: public class UploadNotesActivity extends Activity
line 53: onUploadButtonClick();
Seems like the filePath in line 73 is empty and the way I save filePath into bundle (?) is incorrect. How to get the filePath from onActivityResult? Here's the .java class, just in case. Thank you in advance. Really need your help.
An Intentobject is used to pass params between activities. Ones you receives the file path you must to keep it in your activity.
Create a filePathvariable inside your activity, set it on onActivityResult and read it on onUploadButtonClick.
Notice that must save variable value during the onSaveInstanceState callback and restore it in onCreate because every time you turn your phone the activity is destroyed and recreated. Check this for more information: Recreating an Activity

onActivityResult shows null for intent-data [duplicate]

I'm new to android . This might be the simplest question of all !! but I couldn't figure out whats gone wrong here,
I was trying to create a basic example for passing values through intent.So I need to pass data to Main Activity when I close my Second Activity here is the code
IntentTest1(MainActivity)
public void onClick(View arg0) {
// TODO Auto-generated method stub
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(getApplicationContext(),SecondPage.class);
startActivityForResult(myIntent,0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == 0 && resultCode == RESULT_OK)
if(data.hasExtra("title"))
{
MyClass.myToast(""+resultCode+""+requestCode, getApplicationContext());
String str = data.getExtras().getString("title").toString();
titleText.setText(str);
}
super.onActivityResult(requestCode, resultCode, data);
}
SeconPage
public void finish()
{
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Welcome Back!!","title");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}
I think there is some mistake in receiving the intent ,I couldn't figure out.
Answers and Advises are needed
thanks in advance
The first problem is when you create your Intent to send back to the first Activity. Since you are using startActivityForResult() you want to use an empty constructor. So change
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
to
Intent returnIntent = new Intent();
The second problem is that you have your key/value pair backwards in your Extras. The key, which is what you look for with getStringExtra() etc... should be the first in the pair. So this
returnIntent.putExtra("Welcome Back!!","title");
should be
returnIntent.putExtra("title", "Welcome Back!!");
Off-topic
I would consider using relevant names as your params. For example, I would change your onClick() from
public void onClick(View arg0)
to
public void onClick(View view)
view, v, or something similar makes more sense since the argument actually is a view and it will be more readable
I would also recommend using the Activity Context for your Intent which you can get from the argument (the View) passed into onClick(). So change it to
public void onClick(View v)
{
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(v.getContext(),SecondPage.class);
startActivityForResult(myIntent,0);
You have to use
if(data.hasExtra("Welcome Back!!"))
instead of
if(data.hasExtra("title"))
in onActivityResult. Welcome Back!! is the key and title is the value for that key in your extras.
try this code:
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Key name here in ur case title","Value name");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}

Categories

Resources