onActivityResult data is null for web search - android

My data is returning null for some reason after the I perform a web search. What I am trying to do, and I am not 100% sure if I am on the right track, is to grab all of the possible links from a web search. So if the user types in say "Java", my onActivityResult should be able to find all the links associated with the serach "Java", but right now my data is null.
Here is what I have:
public void onSearchClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
String term = editTextInput.getText().toString();
intent.putExtra(SearchManager.QUERY, term);
startActivityForResult(intent, REQ_CODE_SEARCH);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "FAILED TO CONNECT", Toast.LENGTH_SHORT);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SEARCH: {
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> urls = data
.getStringArrayListExtra(SearchManager.QUERY);
for(int i = 0; i < urls.size(); i++){
System.out.println("************** " + urls.get(i));
}
}
else if(data == null){//goes here
System.out.println("null***********");
}
break;
}
}
If it helps, here is what I do when I run the program:
type in something for the edit text
press a button which does a web search for the content of the edit text
once I reach the google search results, I press the back button, which leads me back to the first screen
the results are then displayed, in this case NULL

Related

setResult(<resultCode> , <Intent>) does not work

I'm trying to pass byteArray and just a String from a current activity to a previous fragment.
public void uploadClick (View view) {
//Send results back to previous screen
switch (activity.from) {
case "review" :
if (activity.mCurrentPhotoPath != null && activity.bytes != null) {
Intent reviewReturnIntent = new Intent();
reviewReturnIntent.putExtra(ReviewsFragment.REVIEW_PHOTO_BITMAP, activity.bytes);
reviewReturnIntent.putExtra(ReviewsFragment.REVIEW_PHOTO_PATH, activity.mCurrentPhotoPath);
activity.setResult(Activity.RESULT_OK, reviewReturnIntent);
activity.finish();
}
break;
case "reply" :
break;
case "merchant" :
break;
}
}
Fragment onActivityResult :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REVIEW_REQUEST) {
if (resultCode == getActivity().RESULT_OK) {
if (data != null) {
returnedBitmap = data.getByteArrayExtra(REVIEW_PHOTO_BITMAP);
returnedPhotoPath = data.getStringExtra(REVIEW_PHOTO_PATH);
Bitmap bmp = BitmapFactory.decodeByteArray(returnedBitmap, 0, returnedBitmap.length);
binding.reviewIV.setImageBitmap(bmp);
binding.returnedImageLayout.setVisibility(View.VISIBLE);
}
}
}
}
startActivityForResult call:
public void uploadClick (View view) {
Intent uploadPhotoIntent = new Intent(fragment.getContext(), UploadPhotoActivity.class);
uploadPhotoIntent.putExtra(UploadPhotoActivity.FROM, "review");
fragment.startActivityForResult(uploadPhotoIntent, ReviewsFragment.REVIEW_REQUEST);
}
Every time I try to run the activity.setResult with an intent parameter. The compiler runs that code, but does not finish the activity (therefore I could not return to the previous fragment / activity).
I've added breakpoints and it runs the "setResult" and the "activity.finish()" methods. But it just doesn't seem to destroy the current activity.
Although, after taking out the intent parameter from the "setResult" method, everything works fine, but on the previous fragment I'm getting a null returned from "data".
Example :
activity.setResult(Activity.RESULT_OK);
Been trying to look for answers around the internet, still no luck.
Would really appreciate it , and thanks for reading. :)

How to handle getResults from multiple activities?

I am trying to get results back from intents in android studio.
In my main I start an activity and use startActivityForResult(intent, 1)
I then use get results in mainActivity from activity 2's setResults()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FIRSTNAME");
String Lname = extras.getString("LASTNAME");
int ID = extras.getInt("ID");
//TODO: Get the list fragment to newinstance with out new arraylist
Person p = new Person(name, Lname, ID);
people.add(p);
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
In my fragment in activity 1 I am calling a new startActivityForResult(i, 2)
How do i get my main activity to grab the setResults()
from Activity 3?
Activity 3 is doing this:
Intent deleteIntent = new Intent();
deleteIntent.putExtra("FNAME", first);
deleteIntent.putExtra("LNAME", last);
deleteIntent.putExtra("ID", num);
setResult(RESULT_OK, deleteIntent);
finish();
I am trying to have my main activity call if (requestCode == 2)
But it works to no avail.
Here is the all the onActivityResult for reference:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FIRSTNAME");
String Lname = extras.getString("LASTNAME");
int ID = extras.getInt("ID");
//TODO: Get the list fragment to newinstance with out new arraylist
Person p = new Person(name, Lname, ID);
people.add(p);
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
// NOW SEEING IF THE DETAILS SCREEN PASSED BACK RESULTS
} else if (requestCode == 2) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FNAME");
String Lname = extras.getString("LNAME");
int ID = extras.getInt("ID");
Person p = new Person(name, Lname, ID);
// Delete happens here //
if (people.contains(p)) {
people.remove(p);
// If empty show blank frag, if not, update list //
if (people.isEmpty()) {
getFragmentManager().beginTransaction().replace(R.id.content_main, BlankList.newInstance());
} else {
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
} else {
Toast.makeText(this, "DIDNT RECEIVE SAME INFO", Toast.LENGTH_SHORT).show();
}
}
}
}
// END ELSE CHECK
}
}
Here is the code that is calling the startActivityForResult() in the Fragment on activity 1.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//super.onListItemClick(l, v, position, id);
ArrayList<Person> people = (ArrayList<Person>) getArguments().getSerializable(ARG_People);
if (people != null && position != -1) {
Person listPerson = people.get(position);
Intent i = new Intent("OPENDETAILS");
i.putExtra("NAME", listPerson.name);
i.putExtra("LASTNAME", listPerson.lName);
i.putExtra("ID", listPerson.ID);
startActivityForResult(i, 2);
} else {
Toast.makeText(getActivity(), "EMPTY LIST ERROR", Toast.LENGTH_SHORT).show();
}
}
It's a little unclear what you're trying to do, but it sounds like:
Activity1 starts Activity2 for result
Activity2 starts Activity3 for result
Activity3 returns a result
Activity1 is expected receive Activity3's result.
If I got that right then the key element that seems to be missing here is that you are expecting Activity1 to get a result from Activity3 even though it was Activity2 that started it for result. In this case you should implement onActivityResult in Activity2, handle the results coming back from Activity3 and set them as Activity2's results to pass back to Activity1 and then finish; An activity will only receive results from activities it directly starts via startActivityForResult.
Use different code to launch different activities,
such as
startActivtityForResult(new Intent(this,Person1.class),1);
startActivtityForResult(new Intent(this,Person2.class),2);
startActivtityForResult(new Intent(this,Person3.class),3);
then on activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
//implement your code here
break;
case 2:
//implement your code here
break;
case 3:
//implement your code here
break;
}
}
then set Retrun result in these classes
Person1.class
return_intent.putExtra("result", 1);
setResult(1, return_intent);
Person2.class
Person1.class
return_intent.putExtra("result", 2);
setResult(2, return_intent);
Person3.class
Person1.class
return_intent.putExtra("result", 3);
setResult(3, return_intent);

print text from voice recognition in text view , except the first

I am using simple voice recognition .
I got it successfully working .
Lets say i spoke "Remark hey this is stack overflow"
I want to exclude "Remark" and print the rest of the text in a TextView.
Following is my work onActivityResult :-
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
if(textMatchList.get(0).contains("Field"))
{
Intent non_field = new Intent(DashboardActivity.this,NonFieldActivity.class);
startActivity(non_field);
}
else if(textMatchList.get(0).contains("Tour"))
{
Intent non_field = new Intent(DashboardActivity.this,TourPlanActivity.class);
startActivity(non_field);
}
else {
final Dialog list_dialog;
ListView voice_match_list;
list_dialog = new Dialog(this);
list_dialog.setTitle("Matches");
list_dialog.setCancelable(true);
list_dialog.setContentView(R.layout.voice_list_dialog);
voice_match_list = (ListView) list_dialog.findViewById(R.id.voice_list);
voice_match_list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
Button cancel_button = (Button) list_dialog.findViewById(R.id.cancel_button_voice);
assert cancel_button != null;
cancel_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_dialog.dismiss();
}
});
list_dialog.show();
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Helper method to show the toast message
**/
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
My studies from google:-
.replace can be useful here, not able to understand how to use it with my code. Can some one suggest me article or help me with certain logic ?
you can do it by split method.
String message = "Remark hey this is stack overflow";
String [] arr = message.split(" ", 2);
Now arr[0] will contain "Remark" and arr[1] will contain "hey this is stack overflow"

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)

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();
}
}
}

Categories

Resources