Wait result from intent user - android

my code :
public void run() {
while (!done){
try {
this.mListMessagesResponse = service.users().messages().list(userId).setQ("to:" + recipient).execute().getMessages();
done = true;
} catch(UserRecoverableAuthIOException e) {
mActivity.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
//wait result
} catch (IOException e) {
e.printStackTrace();
}
}
}
i want wait the result from my user to start again my loop.
i tried with wait but it doesn't work.

You don't need a while loop to get the result from an Activity. There is already a build-in function to do that. It's onActivityResult
From the docs:
Start the Activity
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
Use onActivityResult to get the result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
See here for more Getting a Result from an Activity

Related

onActivityResult not called in Android

I have the following code
public void changeContentOnClick(View view) {
Intent intent = new Intent(this, ChangeNodeContentActivity.class);
intent.putExtra("SELECTED_NODE_ID", selectedNode.getNodeId());
intent.putExtra("SELECTED_NODE_CONTENT", selectedNode.getNodeContent());
startActivityForResult(intent,RESULT_OK);
Log.d(TAG, "Can I get here?");
onActivityResult(RESULT_OK, RESULT_OK, intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String editedNodeId = data.getStringExtra("EDITED_NODE_ID");
String editedNodeContent = data.getStringExtra("EDITED_NODE_CONTENT");
Node nodeChecker = new Node(editedNodeId);
Node editedNode = new Node(editedNodeId, editedNodeContent);
Log.d(TAG, editedNode.toString());
nodes.set(nodes.indexOf(nodeChecker), editedNode);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
Somehow, after startActivityForResult method is called, everything stops. The log with message "Can I get here?" is never printed and I don't understand why not. I have followed the answer to this topic, but somehow couldn't make it work. Do I call the onActivityResult in the wrong way or place? Please help me out!
The that should send back some info from the ChangeNodeContentActivity and the one that handles the result code is the following on click listener:
public void changeContentOnClick(View view) {
Intent intent = getIntent();
selectedNode.setNodeContent(nodeContentDisplay.getText().toString());
intent.putExtra("EDITED_NODE_ID", selectedNode.getNodeId());
intent.putExtra("EDITED_NODE_CONTENT", selectedNode.getNodeContent());
setResult(RESULT_OK, intent);
Log.d(TAG, selectedNode.toString());
finish();
}
startActivityForResult() method receives an intent and requestCode, so you should change it to:
startActivityForResult(intent, REQUEST_CODE)
And onActivityResult() method is automatically called when returning from the activity, so you should remove the direct call you made to the method, i.e. onActivityResult(RESULT_OK, RESULT_OK, intent)

How to respond to 'attach' from Gmail? Responding to intent with attachment

I am writing an android application. This app is built on top of Gmail. I want to add the ability to attach files from other apps. The first app I am working on doing this with is a custom Box app (made with the box sdk). I can currently send an intent, open an activity in the Box app, pick an attachment, and return. However, in my Box-SDK app, once an item is selected, I have no idea how to turn it into data that I can properly send back to my Gmail app (or any original sender of the intent). I also do not know how to send that data back to the originator of the intent.
I know setResult() is involved, but I am not sure where to put it or how to properly use it to carry the data chosen in box into the email app.
What's currently happening is it just goes back into gmail without an attachment and says that the download has finished.
Here is the code I currently have:
private void onFileSelected(final int resultCode, final Intent data) {
if (Activity.RESULT_OK != resultCode) {
Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
}
else {
final BoxAndroidFile file = data.getParcelableExtra(FilePickerActivity.EXTRA_BOX_ANDROID_FILE);
AsyncTask<Null, Integer, Null> task = new AsyncTask<Null, Integer, Null>() {
#Override
protected void onPostExecute(Null result) {
Toast.makeText(MainActivity.this, "done downloading", Toast.LENGTH_LONG).show();
// Intent result2 = new Intent();
// result2.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + ));
// setResult(Activity.RESULT_OK, result2);
//// setResult(resultCode, data);
super.onPostExecute(result);
finish();
}
#Override
protected void onPreExecute() {
Toast.makeText(MainActivity.this, "start downloading", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected Null doInBackground(Null... params) {
BoxAndroidClient client = ((HelloWorldApplication) getApplication()).getClient();
try {
File f = new File(Environment.getExternalStorageDirectory(), file.getName());
Intent result2 = new Intent();
result2.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + f.getAbsolutePath()));
setResult(Activity.RESULT_OK, data);
// setResult(resultCode, data);
System.out.println(f.getAbsolutePath());
client.getFilesManager().downloadFile(file.getId(), f, null, null);
}
catch (Exception e) {
}
return null;
}
};
task.execute();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUTH_REQUEST) {
onAuthenticated(resultCode, data);
}
else if (requestCode == UPLOAD_REQUEST) {
onFolderSelected(resultCode, data);
}
else if (requestCode == DOWNLOAD_REQUEST) {
onFileSelected(resultCode, data);
}
}
Try using a file provider:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html#ServeUri
From the page:
"There are a variety of ways to serve the content URI for a file to a client app. One common way is for the client app to start your app by calling startActivityResult(), which sends an Intent to your app to start an Activity in your app. In response, your app can immediately return a content URI to the client app or present a user interface that allows the user to pick a file. In the latter case, once the user picks the file your app can return its content URI. In both cases, your app returns the content URI in an Intent sent via setResult()"
From another stackoverflow answer:
public void showCameraScreen(View view) {
// BUILT IN CAMERA
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
this.startActivityForResult(camera, 1);
}
private File getTempFile(Context context) {
// it will return /sdcard/MyImage.tmp
final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
if (!path.exists()) {
path.mkdir();
}
return new File(path, "MyImage.tmp");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final File file = getTempFile(this);
byte[] _data = new byte[(int) file.length()];
try {
InputStream in = new FileInputStream(file);
in.read(_data);
in.close();
in = null;
//DO WHAT YOU WANT WITH _data. The byte array of your image.
} catch (Exception E) {
}
}
}
We can modify this code, where it says //Do What you want with the _data, just call
public final void setResult (int resultCode, Intent data)

OnActivityResult not called on device

I try to select contact from contacts list:
contactsButton.Click += (object sender, EventArgs e) =>
{
//Create a new intent for choosing a contact
var contactPickerIntent = new Intent(Intent.ActionPick, Android.Provider.ContactsContract.Contacts.ContentUri);
//Start the contact picker expecting a result
// with the resultCode '101'
StartActivityForResult(contactPickerIntent, 101);
};
and method OnActivityResult called under xamarin debugger and not called on my real device (SGS4).
When user cancels operation in contacts list, method OnActivityResults called under debugger and on real device.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
phoneNumberText.Text = String.Format("request={0}, result={1}", requestCode, resultCode);
base.OnActivityResult(requestCode, resultCode, data);
...
}
update:
I don't understand why, but next line solves the issue: contactPickerIntent.SetType(ContactsContract.CommonDataKinds.Phone.ContentType);
contactsButton.Click += (object sender, EventArgs e) =>
{
//Create a new intent for choosing a contact
var contactPickerIntent = new Intent(Intent.ActionPick, Android.Provider.ContactsContract.Contacts.ContentUri);
contactPickerIntent.SetType(ContactsContract.CommonDataKinds.Phone.ContentType);//(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
//Start the contact picker expecting a result
// with the resultCode '101'
StartActivityForResult(contactPickerIntent, 101);
};
line contactPickerIntent.SetType(...) somehow fixes the issue.
contactsButton.Click += (object sender, EventArgs e) =>
{
//Create a new intent for choosing a contact
var contactPickerIntent = new Intent(Intent.ActionPick, Android.Provider.ContactsContract.Contacts.ContentUri);
contactPickerIntent.SetType(ContactsContract.CommonDataKinds.Phone.ContentType);//(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
//Start the contact picker expecting a result
// with the resultCode '101'
StartActivityForResult(contactPickerIntent, 101);
};
I have never used xamarin but in terms of Android dev try changing the code onActivityResult code to:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
....
}

Use onactivityresult android

I want to call a method from mainactivity in other activities. For that, I've researched a lot and found that using OnActivityResult is the best option. Can anyone please explain how to use this method with the help of an example? I've gone through similar questions but found them confusing.
Thanks!
EDIT:I have a custom dialog activity in my app. It asks the users whether they want to start a new game or not and it has two buttons yes and no. I want to implement the above method only to get the pressed button.
Define constant
public static final int REQUEST_CODE = 1;
Call your custom dialog activity using intent
Intent intent = new Intent(Activity.this,
CustomDialogActivity.class);
startActivityForResult(intent , REQUEST_CODE);
Now use onActivityResult to retrieve the result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra("key");
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
In custom dialog activity use this code to set result
Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();
Start the Activity:
you do need to pass an additional integer argument to the startActivityForResult() method.You may do it by defining a constant or simply put an integer.The integer argument is a "request code" that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
static final int ASK_QUESTION_REQUEST = 1;
// Create an Intent to start SecondActivity
Intent askIntent = new Intent(FirstActivity.this, SecondActivity.class);
// Start SecondActivity with the request code
startActivityForResult(askIntent, ASK_QUESTION_REQUEST);
Return The Result:
After completing your work in second activity class simply set the result and call that activity where it comes from and lastly don't forget to write finish() statement.
// Add the required data to be returned to the FirstActivity
sendIntent.putExtra(Result_DATA, "Your Data");
// Set the resultCode to Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(RESULT_OK, sendIntent);
// With finish() we close the SecondActivity to
// return to FirstActivity
finish();
Receive The Result:
When you done with the subsequent activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:
#The request code you passed to startActivityForResult().
#A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the operation failed
#An Intent that carries the result data.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 1
if (requestCode == ASK_QUESTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
final String result = data.getStringExtra(SecondActivity.Result_DATA);
// Use the data - in this case display it in a Toast.
Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
}
}
}
This is my example.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Image_Request_Code && resultCode ==RESULT_OK && data != null && data.getData() != null) {
FilePathUri = data.getData();
try {
// Getting selected image into Bitmap.
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
// Setting up bitmap selected image into ImageView.
SelectImage.setImageBitmap(bitmap);
// After selecting image change choose button above text.
ChooseButton.setText("Image Selected");
}
catch (IOException e) {
e.printStackTrace();
}
}*strong text*
if (requestCode == 2000)
{
if (resultCode == Activity.RESULT_OK)
{
try {
Uri selectedImages = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImages,
filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
receivedImageBitmap = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(receivedImageBitmap);
}
catch (Exception e)
{
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}

How can I open the Contacts activity just to view the contact's information, not allowing the user to click (or touch) anything?

I want to open the native Contact activity, not the Contacts list as I already have done that, but a particular contact information using the native activity.
The special requirement here is that all I want is to display the contact's information but not allowing the user to click anything.
I can open the activity with this code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != 1) {
return;
}
if(resultCode != Activity.RESULT_OK) {
return;
}
Uri selectedUserUri = data.getData();
this.onContactSelected(selectedUserUri);
}
private void onContactsButtonClick() {
startActivityForResult(new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI), 1);
}
private void onContactSelected(Uri selectedUserUri) {
startActivityForResult(new Intent(Intent.ACTION_VIEW, selectedUserUri), 2);
}
I need the user not to be able to click anything because that's not part of the functionalities of my application, in the worst case I would need the activity to report me the clicked phone number or e-mail address instead of opening the dialer or a web browser.
Any help will be greatly appreciated.
Mike
Try this below code for start pick contacts activity like this code write button click event contacts:
try
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
catch (Exception e) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
after get contact phone number below code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
try
{
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));
String phone=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phoneNumber="test";
if ( phone.equalsIgnoreCase("1"))
phone = "true";
else
phone = "false" ;
if (Boolean.parseBoolean(phone))
{
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();
}
Toast.makeText(this, "You are selected Contact name "+name, Toast.LENGTH_LONG).show();
if(phone_no.getText().length()!=0)
{
phone_no.setText(phone_no.getText().toString()+","+phoneNumber);
}
else
{
phone_no.setText(phoneNumber);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
this function pick a contact assign phone_no Editext this is not allow make a call!
Note:this function copy paste after onCreate() method like below format:
#Override
public void onCreate(Bundle savedInstanceState) {
------------Your Code ---------
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
------------
}

Categories

Resources