I added onClick() button in fragment to display the result. I also added onActivityResult() method in MyActivity. I want to add onClick() button in more fragments and also show results.
In that case how I should write multiple onActivityResult() method in activity?
Below is my code for OnActivityResultmethod:
button = (Button) view.findViewById(R.id.zing);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.initiateScan();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode,
data);
Fragment fragment = this.getFragmentManager().findFragmentById(R.id.total_frame_content);
if (fragment instanceof CustomerIdFragment) {
if (scanResult != null) {
if (scanResult.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
} else {
//String customerSno = scanResult.getContents().substring(0, 10),
// passCode = scanResult.getContents().substring(10, 14);
Toast.makeText(this, " " + scanResult.getContents(), Toast.LENGTH_SHORT).show();
// System.out.println("Result" + scanResult.getContents());
}
}
}
}
Try This u can not overide method multiple time so u pas int value
startActivityForResult(intent,1);
in on activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
if(resultCode == RESULT_OK){
//do somthing
}
}
if(requestCode == 2){
if(resultCode == RESULT_OK){
//do somthing
}
}
if(requestCode == 3){
if(resultCode == RESULT_OK){
//do somthing
}
}
}
Edited Answer
In Your Fragment java File
private int PICK_IMAGE_REQUEST_CODE = 1;
btChoseFile = (Button)view.findViewById(R.id.btChoseFile);
btStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST_CODE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST_CODE){
Toast.makeText(getActivity(),"On Activity Result in fragment",Toast.LENGTH_LONG).show();
}
}
You just need to use switch case for that like below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
if (requestCode == REQUEST_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK ) {
//your code
break;
case PHOTO_PICKER_ID:
if (requestCode == PHOTO_PICKER_ID && resultCode == Activity.RESULT_OK && null != data) {
//your code
}
break;
}
} catch (Exception e)
{
Log.d("krvrrusbviuritiribtr", e.getMessage());
}
}
When you call startActivityForResult(intent,requestCode);, you just need to use different requestCode. This number will be send to the onActivityResult(requestCode, resultCode, intent)
Create some constants for the request in your activity (call it MyActivity).
public class MyActivity{
private static final int REQUEST_ONE = 1;
private static final int REQUEST_TWO = 2;
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//Management of the result, see below
}
}
Use the constant corresponding to the request calling.
//startActivityForResult(intent,REQUEST_CODE);
In you first fragment, you will use
public void clickButton(View v){
startActivityForResult(intent,MyActivity.REQUEST_ONE);
}
In the second fragment, you will use
public void clickButton(View v){
startActivityForResult(intent,MyActivity.REQUEST_TWO);
}
Then you just need to implements the result method in the activity to take care of the requestCode value to execute the correct code. Using a switch or if else conditions. There are more possibilities (using some pattern) but the easiest are those.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == REQUEST_ONE){
// the code for request one
} else if(requestCode == REQUEST_TWO){
// the code for request two
} else {
super.onActivityResult(requestCode, resultCode, intent);
}
}
or with a switch
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch(requestCode)
case REQUEST_ONE:
// the code for request one
break;
case REQUEST_TWO:
// the code for request two
break;
default:
super.onActivityResult(requestCode, resultCode, intent);
}
}
If you have too much request, create one method for each requests, this will keep the result method more readable.
Related
I have two button in my activity to scan. But how can i differentiate between each one in on activityForResult? I know I should be using StartActivityforResult() and pass a number for each scan but I couldn't figure out how to do it with integrator.
ibBinScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scan();
}
});
ibNumberScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scan();
}
});
public void scanNow() {
IntentIntegrator integrator = new IntentIntegrator(InboundActivity.this);
integrator.setCaptureActivity(Portait.class);
integrator.setOrientationLocked(false);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan Barcode");
integrator.initiateScan();
}
#SuppressLint("SetTextI18n")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (requestCode == 1) {}
if (requestCode == 2) {}
} else super.onActivityResult(requestCode, resultCode, data);
}
you can use :
integrator.setRequestCode(REQUEST_CODE);
IntentIntegrator fro zxing does have a request code setter for Intent. Try this way :-
public static final int REQ_CODE1=23;
public static final int REQ_CODE2=25;
public void scanNow(int requestCode) {
IntentIntegrator integrator = new IntentIntegrator(InboundActivity.this);
integrator.setCaptureActivity(Portait.class);
integrator.setOrientationLocked(false);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan Barcode");
integrator.setRequestCode(requestCode)
integrator.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if((requestCode==REQ_CODE1 || requestCode==REQ_CODE2) && resultCode==RESULT_OK){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(requestCode==REQ_CODE1){
}else(requestCode==REQ_CODE2){
}
}else{
}
}
In my application i have one activity (MainActivity) and some fragments (ServicesFragment , NewAddressFragment).
ServicesFragment used in viewPager and NewAddressFragment used getFragmentManager().replace ... for show this fragments!
in this fragments i used onActivityResult, but get conflict in one of fragments not call codes of onActivityResult codes in one of fragments.
I write below codes, please see this.
MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
}
ServiceFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("BazaarPaymentLog", "Result");
Log.e("BazaarPaymentLog", "bazaarRequestCode : " + bazaarRequestCode);
if (iabHelper == null) return;
if (requestCode == bazaarRequestCode) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
purchaseToken = jo.getString("purchaseToken");
productId = jo.getString("productId");
packageName = jo.getString("packageName");
Log.e("BazaarPaymentLog", "purchaseToken : " + purchaseToken);
if (iabHelper != null) {
iabHelper.handleActivityResult(requestCode, resultCode, data);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
NewAddressFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
if (data != null) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
postPath = mediaPath;
uploadImageToServer(postPath);
}
} else if (requestCode == CAMERA_PIC_REQUEST) {
if (Build.VERSION.SDK_INT > 21) {
postPath = mImageFileLocation;
} else {
postPath = fileUri.getPath();
}
uploadImageToServer(postPath);
}
} else if (resultCode != RESULT_CANCELED) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
When write onActivityResult code in MainActivity, in ServicesFragment call onActivityResult codes and in NewAddressFragment not call onActivityResult codes.
But When remove onActivityResult code in MainActivity, in ServicesFragment not call onActivityResult codes and in NewAddressFragment call onActivityResult codes.
How can i fix it?
Inside onActivityResult of MainActivity use this :
Instead of this :-
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
}
Use this :-
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
for(Fragment fragment : getSupportFragmentManager().getFragments()){
fragment.onActivityResult(requestCode,resultCode,data);
}
}
let me know if it is working or not
please add this line to onActivityResult in activity
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
Fragment addressFrag = findFragmentByTag("NewAddressFragmentTag");
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
if (addressFrag instanceof NewAddressFragment) {
((NewAddressFragment) addressFrag).onActivityResult(requestCode, resultCode, data);
}
}
I can resolved my problem!
Change MainActivity codes with below codes :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
Fragment addressFrag = getSupportFragmentManager().findFragmentByTag("NewAddressFragmentTag");
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
if (addressFrag instanceof NewAddressFragment) {
super.onActivityResult(requestCode, resultCode, data);
}
}
I hope help this for another dear developers
I am making a mailing app. What I want to do is open list chooseContactsActivity from composeMailActivity, select some contacts and click add to send them back to composeMailActivity. First thing I did was that standard passing between activities where I passed a string, and the correct string was passed and recognized in composeMailActivity. Then I added arrayList of strings - of contact ids. In chooseContactsActivity it is recognized correctly when debugging, but in the composeMailActivity it returns null.
Some of the answers I tried include: 1, 2, 3, 4, 5...
ChooseContactsActivity:
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<String> selectedIds = adapter.selectedIds;
String text = "abc";
Intent intent = new Intent();
intent.putStringArrayListExtra("contacts_added", selectedIds);
setResult(RESULT_OK, intent);
finish();
}
});
ComposeMailActivity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
ArrayList<String> get_contacts = getIntent().getExtras().getStringArrayList("contacts_added");
}
}
}
You should use the data Intent in onActivityResult(int requestCode, int resultCode, Intent data) instead of getIntent()
like this
if (resultCode == RESULT_OK) {
ArrayList<String> get_contacts = data.getExtras().getStringArrayList("contacts_added");
}
I think try to get "contacts_added" form "data". Instead of calling getIntent() try
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
ArrayList<String> get_contacts = data.getExtras().getStringArrayList("contacts_added");
}
}
}
Hope this will solve your problem.
Just trying to flatten out bugs..
Int can not be dereferenced (on the StartWith Line)
Cannot find symbol method parse(int)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BARCODE_READER_REQUEST_CODE) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (resultCode.Startswith("http://") || resultCode.startsWith("https://")) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, URI.parse(resultCode));
startActivity(browserIntent);
}
Here is the solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BARCODE_READER_REQUEST_CODE) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
String value = barcode.displayValue;
if (value.startsWith("http://") || value.startsWith("https://")) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(value));
startActivity(i);
}
} else
{
Log.e("your_tag","no value captured");
}
} else Log.e("your_tag","barcode error ");
} else super.onActivityResult(requestCode, resultCode, data);
}
I have created two edit texts. And i created two buttons. By clicking on a button, it will ask for user to speak and it will convert the speech to text and it will
be displayed in the edit text.
I have called the voice to text function two times. One for first edit text and other for second edit text. But it displaying the error.
Please help me to solve this problem.
Here is my code:
private void promptSpeechInput1() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput1.setText(result.get(0));
}
break;
}
}
}
//////////////
private void promptSpeechInput2() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput2.setText(result.get(0));
}
break;
}
}
}
And the error shows on the line:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
You are redefining the onActivityResult method. Use only one instance for your purpose
/**
* Receiving speech input and output
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput1.setText(result.get(0));
}
break;
}
case REQ_CODE_SPEECH_OUTPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput2.setText(result.get(0));
}
break;
}
}
}
and modify this in your promptSpeechInput2 method. Use different request code i.e. not REQ_CODE_SPEECH_INPUT else use REQ_CODE_SPEECH_OUTPUT with different value
try {
startActivityForResult(intent, REQ_CODE_SPEECH_OUTPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}