zxing barcode scanner results in null - android

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

Related

Freeze activity after Dialog prompt on onActivityResult function

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

Disable button in a Listview's row while getting response of a save?

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

onActivityResult() is not calling in fragment

I want to scan QR Code in fragment.
But onActivityResult is not calling.
Fragment.java
#Override
public View onCreateView(LayoutInflater inflater ,ViewGroup container ,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_offer ,container ,false );
scanOffer = view.findViewById( R.id.scanOffer );
scanOffer.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
scanBarcode();
}
} );
return view;
}
public void scanBarcode() {
/** This method will listen the button clicked passed form the fragment **/
Intent intent = new Intent(getContext(),CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
uniqueCode = data.getStringExtra("SCAN_RESULT");
Log.d(TAG, "contents: " + uniqueCode);
Toast.makeText( getContext() ,uniqueCode ,Toast.LENGTH_SHORT ).show();
// callAddStoreContestParticipantService();
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "RESULT_CANCELED");
}
}
}
Please help me.
onActivityResult() is not calling
CaptureActivity.class opens Qr after scanning onActivityResult() is not calling
Try below code for barcode scan and also override on activity result in parent activity
private static final int BARCODE_REQUEST = 312;
private void startBarcode() {
//IntentIntegrator.forFragment(getActivity().initiateScan()); // `this` is the current Fragment
IntentIntegrator integrator = new IntentIntegrator(getActivity()) {
#Override
protected void startActivityForResult(Intent intent, int code) {
Fragment.this.startActivityForResult(intent, BARCODE_REQUEST); // REQUEST_CODE override
}
};
//IntentIntegrator integrator = new IntentIntegrator(getActivity());
//IntentIntegrator.forSupportFragment(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.setOrientationLocked(false);
integrator.setTimeout(15000);
integrator.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case BARCODE_REQUEST:
IntentResult Result = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
if (Result != null) {
if (Result.getContents() == null) {
Timber.i("cancelled scan");
showSnackbar("cancelled scan", true);
} else {
Timber.i("Scanned");
showSnackbar("Code scan successfully", false);
try {
long id = Long.parseLong(Result.getContents());
// getFood(id);
searchBarcode(Result.getContents());
} catch (Exception e) {
e.printStackTrace();
}
// searchBarcode(Result.getContents());
//getFood(Long.valueOf(mItem.get(position - 1).getID()));
}
} else {
showSnackbar("Barcode not scanned", true);
Timber.i("Barcode Result is NULL");
super.onActivityResult(requestCode, resultCode, data);
}
break;
}
}
You can get reference from this example:Barcode Scanner
you have to call getActivity().startActivityForResult(intent, 0);
in your fragment
and in your activity you in onActivityResultMethod() you have to call yourfragmnt.onActivityResult()

How to read code 39 using zxing in android?

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

Trying to read barcodes with Zxing, but it seems the onActivityResult is not beeing called

as the title says, I'm trying to scan 1D barcodes, so far I have thet following code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void test(View view){
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "1D_CODE_MODE");
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
IntentResult intentResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null) {
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
TextView uno = (TextView) findViewById(R.id.textView1);
uno.setText(contents);
Toast.makeText(this, "Numero: " + contents, Toast.LENGTH_LONG).show();
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
}
And of course, I have both IntentResult and IntentIntegrator added to the project.
So, the scanner is beeing called correctly when a button is pressed and it seems to scan the code perfectly (it says "Text found" after it scans it), but it seems that the onActivityResult is not called, since the TextView is not beeing updated and the Toast is not appearing.
Any idea on what the mistake could be?
Thanks in advance!
Your first mistake is not using IntentIntegrator.initiateScan(), replacing it with your own hand-rolled call to startActivityForResult().
Your second mistake is in assuming that IntentIntegrator.REQUEST_CODE is 0. It is not.
Hence, with your current code, you are sending out a request with request code of 0, which is coming back to onActivityResult() with request code of 0, which you are ignoring, because you are only looking for IntentIntegrator.REQUEST_CODE.
Simply replace the body of your test() method with a call to initiateScan(), and you should be in better shape. Here is a sample project that demonstrates the use of IntentIntegrator.
I resolve your same problem so.
public class MainActivity extends Activity {
private TextView tvStatus, tvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.tvStatus = (TextView) findViewById(R.id.tvStatus);
this.tvResult = (TextView) findViewById(R.id.tvResult);
Button scanBtn = (Button) findViewById(R.id.btnScan);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_FORMATS", "QR_CODE_MODE");
startActivityForResult(intent,
IntentIntegrator.REQUEST_CODE);
} catch (Exception e) {
Log.e("BARCODE_ERROR", e.getMessage());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
if (scanResult != null) {
this.tvStatus.setText(scanResult.getContents());
this.tvResult.setText(scanResult.getFormatName());
}
}
}
The onActivityResault function must be overridden. just add an #Override before the function declaration and it will be solved.

Categories

Resources