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);
}
}
}
Related
Scenario: App Scans a QR code using Zxing library. When scanning usecase is initiated, app’s main activity launches activity A which initializes the UI , checks the basic permissions (like camera access,) , it then launches activity B for scanning the image. Scanning is done two ways, one is through camera and another is by picking an image from gallery.
What works: Scanning through camera and scanning valid QR code files from the gallery works
Issue: After scanning an invalid QR code from gallery. On pressing back button on the toolbar of activity A, app hangs. On the run window, this message is displayed “SQLiteConnectionPool: The connection pool for database '+appname_dbV8' has been unable to grant a connection to thread 2 (main) with flags 0x5 for 16.006 seconds
Activity A:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
Toolbar toolbar = getActionBarToolbar();
toolbar.setTitle("Scan");
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view) {
navigateUpToFromChild(ActivityA.this,
Intent.makeMainActivity(new ComponentName(ActivityA.this,
mymainactivity.class)));
}
});
setEventListeners();
}
private void initiateScan () {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setCaptureActivity(ActivityB.class);
integrator.setOrientationLocked(false);
integrator.initiateScan();
}
private void setEventListeners () {
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Scan cancelled!", Toast.LENGTH_LONG).show();
finish();
} else {
String decoderesult = "";
try {
decoderesult = URLDecoder.decode(result.getContents(), "UTF-8");
} catch (UnsupportedEncodingException e) {
//Log error message
} catch (IllegalArgumentException i) {
//log error message
Toast.makeText(this, "Unsupported scan Code!", Toast.LENGTH_LONG).show();
finish();
}
if (decoderresult is a valid scan code) {
//parse and handle the scan code
} else { //handle invalid QR code
Toast.makeText(this, "Invalid QR Code!", Toast.LENGTH_LONG).show();
finish();
}
}
} else
{
super.onActivityResult(requestCode, resultCode, data);
}
}
Activity B:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
toolbar.setTitle("Scan");
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.zxing_barcode_scanner);
barcodeScannerView.setTorchListener(this);
switchFlashlightButton = (ImageView) findViewById(R.id.switch_flashlight);
// if the device does not have flashlight in its camera,
// then remove the switch flashlight button...
if (!hasFlash()) {
switchFlashlightButton.setVisibility(View.GONE);
}
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
}
//XML file has the corresponding onclick for gallery_browse
public void gallery_browse(View view){
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (data == null || data.getData() == null) {
Log.e("TAG", "The uri is null, probably the user cancelled the image selection process using the back button.");
return;
}
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null) {
Toast.makeText(this, "Not a valid QR code", Toast.LENGTH_LONG).show();
return;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
String data = "";
Result result;
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
try {
result = reader.decode(bBitmap, hints);
resultdata = result.getText();
} catch (IllegalArgumentException i) {
} catch (NotFoundException e) {
ULog.e("Not found exception in class " + getClass().getName(), e.getMessage());
RemoteLogger.b(e.getMessage());
}
if (resultdata is valid) {
// Parse and process the data
}else {
Toast.makeText(this, "Seems to be an Invalid QR Code. Try another QR code!!", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Log.e("TAG", "can not open file" + uri.toString(), e);
}
}
else{
super.onActivityResult(requestCode, resultCode, data);
}
}
Found the issue. In the code which I have provided here, in activity B, after decode, in Notfoundexception block there was a remote logger code which was causing the app to hang and later crash.
This was the part of code that was causing the issue:
ULog.e("Not found exception in class " + getClass().getName(), e.getMessage());
RemoteLogger.b(e.getMessage());
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);
Beginner question...
I have the following 4 lines of code.
The third line asks the user (with speech) whether he / she is certain about an action.
Then the fourth line calls a method called speechYesNo (included below) to listen for the users response.
The problem is that the speechYesNo method is called before the txtSpeech.speak line (3rd line) is finished speaking and it records the "Are you sure... " speech line as well as the users response.
For example, if the user responds "Yes", the result from the speechYesNo method will be something like... "Are you sure you would like to add xxxxx Yes".
I just want the result to be "yes".
Is there a way to force the third line (txtSpeech.speak) to finish before the speechYesNo() method is called?
Thanks
String strCommonName = myUtil.getCommonName(strFinalResult);
String strToSpeak = "Are you sure you would like to add " + strCommonName;
txtSpeech.speak(strToSpeak, TextToSpeech.QUEUE_FLUSH, null);
speechYesNo();
Here is the speechYesNo() method
public void speechYesNo() {
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());
if(intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 9);
} else {
Toast.makeText(context, "Your device does not support Speech Input.", Toast.LENGTH_LONG).show();
}
}
Here is the onActivityResult...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if(resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String strResult = result.get(0);
Double dblStringComparison = 0.000;
String strFinalResult = "Unknown";
for(int intCount = 0; intCount <= arrAnimals.size()-1; intCount++) {
String strVal1 = strResult;
String strVal2 = myUtil.getCommonName(arrAnimals.get(intCount));
Double dblTemp = myUtil.similarity(strVal1, strVal2 );
if(dblTemp > dblStringComparison){
dblStringComparison = dblTemp;
strFinalResult = arrAnimals.get(intCount);
}
}
atvAnimalName.setText(strFinalResult);
String strCommonName = myUtil.getCommonName(strFinalResult);
String strToSpeak = "Are you sure you would like to add " + strCommonName;
txtSpeech.speak(strToSpeak, TextToSpeech.QUEUE_FLUSH, null);
speechYesNo();
}
break;
case 9:
if(resultCode == RESULT_OK && data != null) {
ArrayList<String> result2 = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String strYesNo0 = result2.get(0);
Toast.makeText(context, strYesNo0, Toast.LENGTH_LONG).show();
}
break;
}
}
Here is the full script
The openSpeechMode method will fire when user clicks an image and will record the users speech selection.
Once this is done I want the app to ask the user is he / she is sure about his / her selection.
If the user responds "yes" then I will do some more work.
The problem as per above is the the speech recorder is recording the "are you sure " question as well as the "yes" response.
public void openSpeechMode(View view) {
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());
if(intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(context, "Your device does not support Speech Input.", Toast.LENGTH_LONG).show();
}
}
public void speechYesNo() {
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());
if(intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 9);
} else {
Toast.makeText(context, "Your device does not support Speech Input.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if(resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String strResult = result.get(0);
Double dblStringComparison = 0.000;
String strFinalResult = "Unknown";
for(int intCount = 0; intCount <= arrAnimals.size()-1; intCount++) {
String strVal1 = strResult;
String strVal2 = myUtil.getCommonName(arrAnimals.get(intCount));
Double dblTemp = myUtil.similarity(strVal1, strVal2 );
if(dblTemp > dblStringComparison){
dblStringComparison = dblTemp;
strFinalResult = arrAnimals.get(intCount);
}
}
atvAnimalName.setText(strFinalResult);
String strCommonName = myUtil.getCommonName(strFinalResult);
String strToSpeak = "Are you sure you would like to add " + strCommonName;
txtSpeech.speak(strToSpeak, TextToSpeech.QUEUE_FLUSH, null);
// speechYesNo();
}
break;
case 9:
if(resultCode == RESULT_OK && data != null) {
ArrayList<String> result2 = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String strYesNo0 = result2.get(0);
Toast.makeText(context, strYesNo0, Toast.LENGTH_LONG).show();
}
break;
}
}
Question
The problem is that the speechYesNo method is called before the
txtSpeech.speak
Solution
txtSpeech seems to be TextToSpeech class. thus, you should use UtteranceProgressListener for resolving your problem.
Try as below code.
txtSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
speechYesNo();
}
#Override
public void onError(String utteranceId) {
}
});
txtSpeech.speak(strToSpeak, TextToSpeech.QUEUE_FLUSH, null);
I know there is like a ton topic and question regarding Voice Recognition and my question might be a stupid one too. but please bear with me guys.
I need to get the result of the speech recognition into an (Editable Text Box) instead of (Array List), the editable text box to allow the user to edit the result , just like a memo.
I found some questions like mine but I could not understand ,I am still a beginner comparing to you guys .
This is the code :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private ListView mlvTextMatches;
private Button mbtSpeak;
private Button reButton;
private EditText result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
result = (EditText) findViewById(R.id.out_text);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
mlvTextMatches .setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,textMatchList));
}
}
//Result code for various error.
{
} if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Helper method to show the toast message
**/
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
This is the code after editing :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private Button mbtSpeak;
private Button reButton;
private EditText myEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
myEditText = (EditText) findViewById(R.id.out_text);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
myEditText.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// myEditText.append(match + "\n"); // or whatever separator you want
// }
}
}
the second try is :
} else {
// populate the Matches
//myEditText.setText(textMatchList.toString());
// if the above does not look good
for (String match : textMatchList) {
myEditText.append(match + "\n"); // or whatever separator you want
}
}
}
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
result.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// result.append(match + "\n"); // or whatever separator you want
// }
}
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();
}
});
}
}