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{
}
}
Related
I have 3 classes: MainActivity, HighScoreActivity, and GameScreenActivity. I want to go to the GameScreenActivity via MainActivity, and then when the game has finished, pass the score to the HighScoreActivity. Everything gets passed to the GameScreenActivity successfully, but it doesn't go to the onActivityResult in HighScoreActivity.
I believe it's because of the MainActivity having the startActivityForResult, so the GameScreenActivity's finishQuiz() is expecting to return its data to the MainActivity. How would I pass the GameScreenActivity's data to the HighScoreActivity?
MainActivity()
MainActivity(){
...
private void startQuiz() {
String difficulty = spinnerDifficulty.getSelectedItem().toString();
Intent intent = new Intent(getBaseContext(), GameScreenActivity.class);
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
}
GameScreenActivity()
GameScreenActivity(){
...
private void finishQuiz(){
Intent resultIntent = new Intent(getBaseContext(),
HighScoreActivity.class);
resultIntent.putExtra(EXTRA_SCORE, score);
resultIntent.putExtra(EXTRA_DIFFICULTY, difficulty);
setResult(RESULT_OK, resultIntent);
startActivity(resultIntent);
}
}
HighScoreActivity()
HighScoreActivity(){
...
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
}
-------------------------------------------------------------
Trying with the Broadcast method:
GameScreenActivity() with broadcasting methods
GameScreenActivity(){
...
private void finishQuiz(){
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("scoreEvent");
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
intent.putExtra(EXTRA_SCORE, score);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
sendBroadcast(intent);
Intent goToHighScores = new Intent(getBaseContext(), HighScoreActivity.class);
startActivity(goToHighScores);
}
}
HighScoreActivity() with broadcasting methods
HighScoreActivity(){
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("scoreEvent"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
}
Considering HighScoreActivity is running,
You can utilize LocalBroadcastManager to register local broadcastReceiver in HighScoreActivity with IntentFilter. Also, don't forget to unregister in onDestroy()
Now, instead of setResult do sendBroadcast() from GameScreenActivity
Hope this helps. Happy coding!
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
In my application i want use InAppBillling for buy some features !
I write payment methods into fragment but after show payment dialog and pay by user not show me any data into onActivityResult!
I write log.e into onActivityResult, but again not show.
I think not going into onActivityResult!
My fragment codes :
public class ServicesFragment extends BaseFragment implements IabHelper.OnIabSetupFinishedListener,
IabHelper.QueryInventoryFinishedListener, IabHelper.OnIabPurchaseFinishedListener, IabHelper.OnConsumeFinishedListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_services, container, false);
...
}
#Override
public void onIabSetupFinished(IabResult result) {
if (iabHelper != null) {
iabHelper.flagEndAsync();
//This is call for payment
iabHelper.queryInventoryAsync(ServicesFragment.this);
}
}
#Override
public void onIabPurchaseFinished(IabResult result, final Purchase info) {
//After payment call this
if (result.isSuccess() && info != null) {
handler.post(new Runnable() {
#Override
public void run() {
getCheckBuyFromBazaar(jwtToken, packageName, productId, purchaseToken, buyID, 0, info);
}
});
}
}
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
if (result.isSuccess()) {
bazaarProgressDialog.dismiss();
//Run bazaar dialog
if (iabHelper != null) {
iabHelper.flagEndAsync();
iabHelper.launchPurchaseFlow(activity, bazaarSKU, bazaarRequestCode,
ServicesFragment.this, bazaarHashCode);
}
}
}
#Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess() && purchase != null) {
if (purchase.getSku().equalsIgnoreCase(bazaarSKU)) {
//When purchase consumed
finishPage();
loadingProgressDialog.dismiss();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("BazaarPaymentLog", "Result");
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);
}
}
}
Show me payment dialog and i pay it, but after not going to onActivityResult!
I write above code into activity it's ok and run onActivityResult but into fragment not going into onActivityResult!
How can i fix it?
Actually the result is passed to Activity's onActivtyResult in order to get in Fragment's method you need to pass reult fron Activity to Fragment like below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);
}
and in Fragment call it same as you are calling currently
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
If you are using ViewPager you can get Fragment like below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment mFragment = myPagerAdapter.getItem(mViewPager.getCurrentItem());
if (fragment instanceof ServiccesFragment){
((ServiccesFragment)fragment).onActivityResult(requestCode, resultCode, data);
}
}
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 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.