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.
Related
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);
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 am using zxing in my android application to read QR_CODE and Barcodes. My application is unable to read the CODE_39 using zxing. I am using the following code in CaptureActivity OnResume Method:
Intent intent = getIntent();
String action = intent == null ? null : intent.getAction();
String dataString = intent == null ? null : intent.getDataString();
if (intent != null && action != null) {
if (action.equals(Intents.Scan.ACTION)) {
//Scan the formats the intent requested, and return the
//result
//to the calling activity.
source = Source.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
} else if (dataString != null
&& dataString.contains(PRODUCT_SEARCH_URL_PREFIX)
&& dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
// Scan only products and send the result to mobile Product
// Search.
source = Source.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (dataString != null
&& dataString.startsWith(ZXING_URL)) {
// Scan formats requested in query string (all formats if
// none
// specified).
// If a return URL is specified, send the results there.
// Otherwise, handle it ourselves.
source = Source.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(sourceUrl);
returnUrlTemplate = inputUri
.getQueryParameter(RETURN_URL_PARAM);
decodeFormats = DecodeFormatManager
.parseDecodeFormats(inputUri);
} else {
// Scan all formats and handle the results ourselves
// (launched
// from Home).
source = Source.NONE;
decodeFormats = null;
}
characterSet = intent
.getStringExtra(Intents.Scan.CHARACTER_SET);
Please Help me to solve this issuse. Thanks in advance.
If you are using Android Studio then Add those dependancies-
compile 'me.dm7.barcodescanner:zxing:1.8.3'
compile 'com.journeyapps:zxing-android-embedded:3.0.2#aar'
compile 'com.google.zxing:core:3.2.0'
Zxing Automatically takes code type while scanning
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
Here which is consider all types of codes by default
If you want specific QR then just
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
Use following code-
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class YourActivity extends Activity {
//Barcode Scanning
private ZXingScannerView mScannerView;
// This is your click listener
public void checkBarcode(View v) {
try {
IntentIntegrator integrator = new IntentIntegrator(GateEntryActivity.this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.initiateScan();
//start the scanning activity from the com.google.zxing.client.android.SCAN intent
// Programmatically initialize the scanner view
// setContentView(mScannerView);
} catch (ActivityNotFoundException anfe) {
//on catch, show the download dialog
showDialog(GateEntryActivity.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
//alert dialog for downloadDialog
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
//on ActivityResult method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
Log.d("MainActivity", "Weird");
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
}
The problem I am having with my Alert dialog is that, I have a custom dialog which has 3 edittext end 3 textview on it. when I pick up a contact from contacts I just filled the information in the dilaog edtitext like contactName.setText(bla); however the strange thing happens here that if I cancel the dialog and again pick another contact the details on the dialog is not getting changed and remembers the details from the first picked contact? is int weird? it seems that once it creates the dialog even though if I call the same process creating again the dialog it keeps the first dialog and keeps showing the same dialog. is there anyone whom have had the same experience and know how to solve this?
Here is the code that handles the result comes back from the contact picker.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI,
null, Email.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
contactUEmail=email;
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
// EditText emailEntry = (EditText) findViewById(R.id.invite_email);
// emailEntry.setText(email);
if (email.length() == 0) {
Toast.makeText(this, "No email found for contact.",
Toast.LENGTH_LONG).show();
}
}
showDialog(DIALOG_ADD_NEW_CALL);// this is where I call the dialog.
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
and here is the dialog DIALOG_ADD_NEW_CALL;
case DIALOG_ADD_NEW_CALL:
{
builder = new AlertDialog.Builder(this);
entryView = getLayoutInflater().inflate(R.layout.entry, null);
builder.setView(entryView);
CNameEditor = (EditText) entryView.findViewById(R.id.cName);
CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
if(!contactUEmail.equals(""))//here is the code that I am setting the text.
CEmailEditor.setText(contactUEmail);
else{}
builder.setTitle(R.string.addDialogTitle);
builder.setPositiveButton(R.string.addItem,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancelItem,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
return builder.create();
}
To destroy the dialog, you can call removeDialog. Alternatively, you could override onPrepareDialog and update the dialog before it's shown. Just FYI, both methods are deprecated in favor of DialogFragment along with FragmentManager but you probably have to redo a lot of code to use those.
Override onPrepareDialog
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_ADD_NEW_CALL:
AlertDialog callDialog = (AlertDialog) dialog;
View entryView = callDialog;
CNameEditor = (EditText) entryView.findViewById(R.id.cName);
CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
// do stuff to those variables here
}
}
I have an app that has a user take a picture and have it uploaded to a website.
I have this code right now:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUESTED) {
if(resultCode == RESULT_OK) {
// Maybe add the additional code here?
picture = convertImageUriToFile(imageUri, this);
Thread thread = new Thread(null, uploader, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(pictures.this, "Please wait...", "Uploading data ...", true, true);
}
} else if (requestCode == EXPERIMENT_CODE) {
if (resultCode == Activity.RESULT_OK) {
experimentInput.setText("" + data.getExtras().getInt("edu.cs.h.exp_id"));
}
}
}
However, before the image is downloaded, I want to add a layout that brings up a Spinner (drop down menu) with a list of items that a user can choose from to describe the picture.
What should I add to the code so that before the picture is uploaded, a new layout is displayed, a user makes a selection and hits the OK button on that layout, and then returns back to this piece of code to continue the upload process?
static final int _MY_DIALOG_ = 11;
if(resultCode == RESULT_OK) {
showDialog(_MY_DIALOG_);
}
#Override
protected Dialog onCreateDialog(int id) {
if(id==_MY_DIALOG_){
CharSequence[] shush = new CharSequence[10];
//initialize shush
Dialog dialog = new AlertDialog.Builder(this).setTitle("Select Animation")
.setSingleChoiceItems(shush, 0,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//the user has selected which!!!
dialog.dismiss();
}
}).create();
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface arg0) {
//do what you want now since the user selected!
picture = convertImageUriToFile(imageUri, this);
Thread thread = new Thread(null, uploader, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(pictures.this, "Please wait...", "Uploading data ...", true, true);
}
});
return dialog;
}
return null;
}