I want my application to continue accepting image from the gallery if I chose Upload Image from the dialog box, but the problem is that the function will continue to finish (the log for count is printed even if I didn't pressed any button, and the conditional statement will set cont = false). The decision variable is a global string variable.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean cont = true;
while (cont == true) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
functionHere();
}
if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
if (data != null) {
// this is the image selected by the user
try {
functionHere();
} catch (Exception ex) {
Log.i("Error", ex.toString());
}
}
}
continuePrompt();
if(decision == "Upload"){
requestCode = OPEN_DOCUMENT_CODE;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
else if(decision == "Take Picture"){
//code here
}
else if(decision == "End"){
cont = false;
}
else{
cont = false;
}
Log.d("Count", Integer.toString(count));
}
if (cont == false) {
//output result
}
}
Here is my code for my dialog which I get from another question here in stackoverflow
public void continuePrompt() {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Platelet detection");
builder.setMessage("Are all microscopic slide image uploaded?");
// add the buttons
builder.setPositiveButton("Upload Image", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "Upload";
}
});
builder.setNeutralButton("Take Picture", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "Take Picture";
}
});
builder.setNegativeButton("End", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "End";
}
});
// create and show the alert dialog
builder.show();
}
you still have below line in your code
while (cont == true)
even when you show your dialog this loop is iterating over and over again. you should fix your logic, there shouldn't be any while loop, everything is already in UI thread and with above line you are hanging it showing dialogs one after another. you should show your prompt once and instead of setting global decision variable just place your code response for action in listener
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
functionHere();
continuePrompt();
}
else if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
if (data != null) {
// this is the image selected by the user
try {
functionHere();
continuePrompt();
} catch (Exception ex) {
Log.i("Error", ex.toString());
}
}
}
else{
super.onActivityResult(requestCode, resultCode, data);
}
}
private void continueFlow(){
if("Upload".equals(decision)){
requestCode = OPEN_DOCUMENT_CODE;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
else if("Take Picture".equals(decision)){
//code here
}
}
just call continueFlow(); after every decision change (in every listener). or move code form if("Upload".equals(decision)){ straight to setPositiveButton and so on
btw. decision == "Upload" won't ever be true as == operator is comparing same objects. decision is already declared variable and "Upload" String is freshly created in if statement, its brand new variable. for comparing content of Strings (same text) use stringOne.equals(stringTwo);
Related
Issue:
I have a Listview in Mainactivity. Each row of listview has two buttons say SET and RUN.
Pressing SET will take you to SET activity and if the user clicks save button in SET Activity, I need to disable the SET button in the corresponding row position of the listview in mainactivity.
So Far Done:
For that I have a refresh function on a onclicklistener to requery the list with updated values. How to call that refresh function without keypress in the Mainactivity or is there any other way?
Activity MAIN :
viewHolder.ButtonSET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = v.getTag().toString();
if (title.equals("SET")) {
if (Integer.parseInt((String) viewHolder.TDNQTY.getText()) > 0) {
if(scanoverornot(pos)<=0) {
Intent s = new Intent(DN.this, SETActivity.class);
s.putExtra("position", pos);
s.putExtra("mode", "SET");
try{
startActivityForResult(s, saverequestcode);
// getContext().startActivity(s);
}
catch(Exception e){
Toast.makeText(getContext(),""+e,Toast.LENGTH_LONG).show();
}
}
}
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case saverequestcode:
if (resultCode == RESULT_OK) {
String SItem= data.getStringExtra("SItem");
int SPos= data.getIntExtra("SPos", 0);
saved = 700;
Toast.makeText(getApplicationContext(), ""+ SItem+ SPos, Toast.LENGTH_LONG).show();
//btnvalidate.performClick();
}
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(RESULT_OK, sav);
finish();
You can use startActivityForResult to nail this purpose:
startActivityForResult(new Intent(this, DestinationActivity.class), MY_RESULT);
And then in your MainActivity:
public int MY_RESULT = 10;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_RESULT) {
if (resultCode == Activity.RESULT_OK) {
//refresh the list according to your logic
}
}
}
Don't forget to call setResult(Activity.RESULT_OK); when user clicks save button.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setResult(Activity.RESULT_OK);
}
});
Issue Lines:
Have to add super.onActivityResult(requestCode, resultCode, data);
Removed switch case and used if condition for requestCode check
Solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == saverequestcode) {
if (resultCode == Activity.RESULT_OK) {
String SItem = data.getStringExtra("SItem");
String SPos = data.getStringExtra("SPos");
Toast.makeText(getApplicationContext(), "Item :" + SItem + "Position :" + SPos, Toast.LENGTH_LONG).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Any methods
}
}
else if (requestCode == importrequestcode){
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(Activity.RESULT_OK,sav);
finish();
I have two sets of code. Both sets require the same name onActivityResult but I'm not sure how to combine them without clashing.
The two sets of code are:
1st Set: Users are required to click on the no-image ImageView to select an image from their mobile device and then it will display the image that they have selected.
2nd Set: Users are required to click a Button to scan a barcode. It will open a camera for the user to scan the barcode and after scanning, it will display the number from the barcode.
Here is the code for two sets:
1st Set of Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check for Image Request , If user get the image is ok, and the image is not null
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
//Put the image data into this mImageUri
mImageUri = data.getData();
//This line take the data from mImageUri and load into mImageView so basically changing the uri to image
Picasso.with(this).load(mImageUri).into(ItemORFoodImg);
}
}
2nd Set of Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
final IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result != null){
if(result.getContents() == null){
Toast.makeText(this, "Result Not Found", Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(this);
alertdialogbuilder.setMessage(result.getContents()+"\n\nWant to add as new item?");
alertdialogbuilder.setTitle("ResultScanned");
alertdialogbuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String barcode = result.getContents();
Intent intent = new Intent(BarcodeTest.this,AddNewItem.class);
intent.putExtra(BarID, barcode);
startActivity(intent);
}
});
alertdialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog alertDialog = alertdialogbuilder.create();
alertDialog.show();
}
}
else {
super.onActivityResult(requestCode,resultCode,data);
}
}
Can someone help me combine these two code snippets without clashing?
You can use IntentService.
You can create two java class one for insert code and one for QR code.
When pressed ImageView go to insert code class and when pressed button go to QR code class.
And then pass data to your Activity.
Follow this link
https://developer.android.com/reference/android/app/IntentService
I have an app that will scan Qr code. The Qr code have a default value that if you scan it will go to a dialog box with the result and will call the activity with the same result
I want to happen is when the result of the qr scan is in the dialog box if the result of it is the same with the activity it will open the activity if not it will call a wrong qr.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//We will get scan results here
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
//check for null
if (result != null) {
if (result.getContents() == null) {
// Toast.makeText(this, "Scan Cancelled", Toast.LENGTH_LONG).show();
} else {
//show dialogue with result
showResultDialogue(result.getContents());
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
//method to construct dialogue with scan results
public void showResultDialogue(final String result) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Scan Result")
.setMessage(result)
.setPositiveButton("View your Location", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Scan Result", result);
clipboard.setPrimaryClip(clip);
Intent nxt = new Intent(MainActivity.this, Acad1.class);
startActivity(nxt);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
}
})
.show();
}
No. What i want is when you scan a qr code with the same name with activity it will open first the dialog box and then when you click the view location it will go to the activity with the same name of the result.
I'm trying to read a boarding pass barcode to inform the user if we have details on their flight and if so why not. I'm using AlertDialogs to communicate with the user as Toast notifications did not appear clearly enough. However they dismiss as soon as they are called without the user clicking ok.
How do I stop this? Is onActivityResult the wrong place to put this code?
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String boardingPassString = intent
.getStringExtra("SCAN_RESULT");
Log.d("Scan Result", "contents: " + boardingPassString);
String flightNumber = dataProcessor.decodeFlightNumber(boardingPassString);
Builder dialogBuilder = new AlertDialog.Builder(this);
String isFlightOld = isFlightOld(boardingPassString);
if(isFlightOld.equals(CURRENT))
{
Log.d("Block", "Current");
postData(flightNumber);
}
else if(isFlightOld.equals(TOO_NEW))
{
dialogBuilder.setTitle(R.string.dialog_title_new);
dialogBuilder.setMessage(R.string.dialog_msg_new1 + flightNumber + R.string.dialog_msg_new2);
dialogBuilder.setPositiveButton(android.R.string.ok, null);
AlertDialog alert = dialogBuilder.create();
alert.show();
Log.d("Block", getResources().getString(R.string.dialog_title_new));
}
else if(isFlightOld.equals(OLD))
{
dialogBuilder.setTitle(R.string.dialog_title_old);
dialogBuilder.setMessage(R.string.dialog_msg_old1 + flightNumber + R.string.dialog_msg_old2);
dialogBuilder.setPositiveButton(android.R.string.ok, null);
AlertDialog alert = dialogBuilder.create();
alert.show();
Log.d("Block", getResources().getString(R.string.dialog_title_old));
}
else
{
dialogBuilder.setTitle(R.string.dialog_title_error);
dialogBuilder.setMessage(R.string.dialog_msg_error).show();
dialogBuilder.setPositiveButton(android.R.string.ok, null);
AlertDialog alert = dialogBuilder.create();
alert.show();
Log.d("Block", getResources().getString(R.string.dialog_title_error));
}
} else if (resultCode == RESULT_CANCELED) {
Log.d("Scan Result", "RESULT_CANCELED");
}
}
}
Calling Code
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Testing shortcut
// =================================
// getXMLFlightDetails("US729");
// ==================================
// Uncomment to return Barcode scanning!!!
// =============================================
Intent intent = new Intent(getApplicationContext(),
CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PDF417_MODE");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, 0);
}
});
Just try the following code, hopefully it should work. You need to pass the context in Dialog Builder. Then the Android OS will know which activity the dialog is attached to and where it should be popped.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String boardingPassString = intent
.getStringExtra("SCAN_RESULT");
Log.d("Scan Result", "contents: " + boardingPassString);
String flightNumber = dataProcessor.decodeFlightNumber(boardingPassString);
Builder dialogBuilder = new AlertDialog.Builder(this);
String isFlightOld = isFlightOld(boardingPassString);
if(isFlightOld.equals(CURRENT))
{
Log.d("Block", "Current");
postData(flightNumber);
}
else if(isFlightOld.equals(TOO_NEW))
{
displayAlert(R.string.dialog_msg_new1 + flightNumber + R.string.dialog_msg_new2);
Log.d("Block", getResources().getString(R.string.dialog_title_new));
}
else if(isFlightOld.equals(OLD))
{
displayAlert(R.string.dialog_msg_old1 + flightNumber + R.string.dialog_msg_old2);
Log.d("Block", getResources().getString(R.string.dialog_title_old));
}
else
{
displayAlert(R.string.dialog_msg_error);
Log.d("Block", getResources().getString(R.string.dialog_title_error));
}
} else if (resultCode == RESULT_CANCELED) {
Log.d("Scan Result", "RESULT_CANCELED");
}
}
}
displayAlert(String message)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivity.this);
alertDialog.setTitle(getResources().getString(R.string.alert_title));
alertDialog.setMessage(message);
alertDialog.setPositiveButton(getResources().getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
//your action here
}
});
alertDialog.setNegativeButton(getResources().getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your Action here
}
});
alertDialog.show();
}
If this does not solve your problem. Then you need to show ur entire activity code, as it may be possible that your activity is getting finished soon after the dialog is displayed to the screen.
This turned out to be a multi-threading issue. The method postData used a HTTPResponse call so was not on the main thread. This method would finish a few milliseconds after tyhe dialog had been displayed and was what was dismissing the alertDialogs.
A simple join() call to get the main thread to wait for the postData method to do it's buisness before displaying the alertDialogs was all it took.
I followed guide from this page and I get the intent fired up. It also found barcode. However when
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
showMessage("result", scanResult.toString());
}
// else continue with any other code you need in the method
}
is reached the dialog(showMessage function basically just creates dialog with title and text) shows following text:
Format: null
Contents: null
Raw bytes: (0bytes)
Orientation: null
EC level: null
Have I missed some part or is it just issue with bar codes? I have tried every product with barcode that I have lying around but no change.
My project used to do something like that:
public class MenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_screen);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_menu_screen, menu);
return true;
}
public void onScanCodeClick(View view) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException aex) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("No Application Found");
builder.setMessage("We could not find an application to scan QR CODES."
+ " Would you like to download one from Android Market?");
builder.setPositiveButton("Yes, Please",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri
.parse("market://details?id=com.google.zxing.client.android"));
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks", null);
builder.create().show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
Intent intent2 = new Intent();
intent2.setClass(this, MenuCodeSuccess.class);
intent2.putExtra("qrDetails", contents);
startActivity(intent2);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
onScanCodeClick is just an onClickListener for button. You can of course init your button and use this code instead.
And here is an xml layout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2" >
<Button
android:id="#+id/menuScreen_SCANCODE"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onScanCodeClick"
android:text="#string/scanButton" />
</TableLayout>
Please don't care the style of layout, all what you need is just in java class. :) but it should be working anyway.
// In side onActivityResult(), try this code
if (resultCode == IntentIntegrator.REQUEST_CODE) {
Log.e("inside Request code~~~~~~~~>", "Barcode>>>>");
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, data);
if (scanResult == null) {
Log.e("Scan Result~~~~~~~~>", "value>>> Null");
return;
}
final String result = scanResult.getContents();
final String result1 = scanResult.getFormatName();
if (result != null) {
handlerBarcode.post(new Runnable() {
#Override
public void run() {
// txtScanResult.setText(result);
// txtScanResultFormat.setText(result1);
Toast.makeText(Activity_Form_Data_4.this,
"Code:" + result + " Format:" + result1,
Toast.LENGTH_SHORT).show();
}
});
}
}