I'm trying to develop an Android app that can scan QR codes. But the problem is, it only auto focus on the QR code but not returning any results. Is there a way to fix this?
I'm using zxing libraries.
Hello guys, can someone help me?
I guess you dont have onActivityResult in your code and that is why you cant capture and return any result.
So I am attaching my work and it would help you.
cameraView = (SurfaceView) v.findViewById(R.id.cameraView);
textResult = (TextView) v.findViewById(R.id.textView);
barcodeDetector = new BarcodeDetector.Builder(v.getContext())
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource.Builder(v.getContext(), barcodeDetector)
.setRequestedPreviewSize(640, 640).build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.CAMERA}, RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
textResult.post(new Runnable() {
#Override
public void run() {
//Create vibrate
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textResult.setText(qrcodes.valueAt(0).displayValue);
showResultDialogue(qrcodes.valueAt(0).displayValue);
}
});
}//End if Statement
}
});
Here is the onActivityResult and I think you dont have it.
#Override
public 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) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle("Error");
alertDialog.setMessage("Scanning Error. Please try Again");
alertDialog.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) {
final AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getContext(), android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getContext());
}
//If the text of QR Code is success then Check-in Successful.
//if(result.equalsIgnoreCase("success")){
//Stop the scanner
barcodeDetector.release();
builder.setTitle("Successfully Scan QR Code")
.setMessage("Result ---> " + result)
.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
//Click ok and Back to Main Page
}
}).create().show();
Related
I already got a QR/Barcode Scanner which is working. But I have one problem. The scanner is only reading QR-Codes which contains an url but I want to scan QR-Codes with only text. Does somebody know what the problem could be?
the used library:
implementation 'com.journeyapps:zxing-android-embedded:3.4.0'
method:
private void scanCode() {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setCaptureActivity(CaptureAct.class);
integrator.setOrientationLocked(false);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scanning Code");
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
...
}
hello you need to use follow configuration
compileSdkVersion 28 // Android 9 (API level 28)
minSdkVersion 24 // Android 7.0 (API level 24)
use dependency of google vision in build.gradle of app
implementation 'com.google.android.gms:play-services-vision:17.0.2'
this is the code for scan the qr code
cameraViewQR = findViewById(R.id.cameraView);
cameraViewQR.setZOrderMediaOverlay(true);
qrHolderScreen = cameraViewQR.getHolder();
barcodeQR = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
if (!barcodeQR.isOperational()) {
Toast.makeText(getApplicationContext(), "Problem Occurred in Setup", Toast.LENGTH_SHORT).show();
this.finish();
}
cameraSourcePhone = new CameraSource.Builder(this, barcodeQR)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(24)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(480, 480)
.build();
cameraViewQR.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ContextCompat.checkSelfPermission(ScanActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSourcePhone.start(cameraViewQR.getHolder());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
barcodeQR.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcode = detections.getDetectedItems();
if (barcode.size() > 0) {
Intent intent = new Intent();
intent.putExtra("QRCODE", barcode.valueAt(0));
setResult(RESULT_OK, intent);
finish();
}
}
});
I am trying to get a callback on onRange() of text to speech UtteranceProgressListener. Currently I get callback on onStart(),onEnd().But I can't get callback on onRange().
Can anyone help to get a callback on onRange(). Checked sample codes but not able to find a proper solution.
I think I have to use SynthesisCallback.rangeStart() but I was unable to get any sample code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
tv.setText("Hello how are you");
Intent ttsInstallCheck = new Intent();
ttsInstallCheck.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(ttsInstallCheck, TTS_REQUEST_CODE);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = tv.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
t1.speak(text, TextToSpeech.QUEUE_FLUSH, params);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (TTS_REQUEST_CODE == requestCode) {
if (TextToSpeech.Engine.CHECK_VOICE_DATA_PASS == resultCode) {
t1 = new TextToSpeech(this, this);
t1.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(final String utteranceId) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, utteranceId, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onError(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
}
#Override
public void onRangeStart(String utteranceId, int start, int end, int frame) {
super.onRangeStart(utteranceId, start, end, frame);
Toast.makeText(MainActivity.this, "" + start, Toast.LENGTH_SHORT).show();
}
});
} else {
// not installed
}
}
}
}
I have a Zxing barcode scanner on my app. The result handler when the user scanned the barcode was originally to show the barcode number ina popup on the screen. I want to change this and instead bring the user to a new page where they can see the barcode number and add extra details too like product name, date, category etc. Then when the user clicks save it should add to the firebase database and the barcode number should become the ID.
Then the next time the user scans the same barcode the app will recognise it and show the details you already added.
Here is my code:
public class BarcodeDetect extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
//our database reference object
DatabaseReference databaseFoods;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
//getting the reference of artists node
databaseFoods = FirebaseDatabase.getInstance().getReference("foods");
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(BarcodeDetect.this, "Permission already granted!", Toast.LENGTH_LONG).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(BarcodeDetect.this, CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted){
Toast.makeText(BarcodeDetect.this, "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(BarcodeDetect.this, "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(BarcodeDetect.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onResume() {
super.onResume();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if(scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
Intent intent = new Intent(BarcodeDetect.this, viewBarcode.class);
//starting the activity with intent
startActivity(intent);
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Scan Result");
// builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// scannerView.resumeCameraPreview(BarcodeDetect.this);
// }
// });
// builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
// startActivity(browserIntent);
// }
// });
// builder.setMessage(result.getText());
// AlertDialog alert1 = builder.create();
// alert1.show();
}
}
I have commented out the original code in the event handler and added my own code to bring you to a new page.
This can be thought as a 2 step process:
Pass the data to the next activity
Validate if the data exist in the
database
Once you get the codebar pass it to the next Activity using putExta method
#Override
public void handleResult(Result result) {
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("SOME_KEY", result.getText());
startActivity(intent);
}
Then in the second activity get the extra and validate if it is available in the RTD
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
String codebar = getIntent().getStringExtra("SOME_KEY");
//Once you get the codebar use it as key to query on the Firebase RTD
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
root.child("products").child(codebar).addValueEventListener(...
//Auto generated methods
if (dataSnapshot.exists()) {
//Show the user the data
} else {
//Ask the user to fill a form and upload the data to the same node you are asking for
}
)
}
I made a chatbot using online tutorial, Now apart from writing in edit text as input I am using voice recognition also. but the problem is the tts do not work when I am pressing the voice recognition button. I dont know what is the problem I used various methods. tts works fine while sending text from edit text field. here is the sample for two codes in main activity. First code is for sending text via send button and works fine. Second code is the wone I use stt to chat and tts do not work. Need help to fix the problem. Thanks in advance.
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private FloatingActionButton mButtonSend;
private EditText mEditTextMessage;
private ImageView mImageView;
public Bot bot;
public static Chat chat;
private ChatMessage.ChatMessageAdapter mAdapter;
public Button buSpeak;
public TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
mListView = (ListView) findViewById(R.id.listView);
mButtonSend = (FloatingActionButton) findViewById(R.id.btn_send);
mEditTextMessage = (EditText) findViewById(R.id.et_message);
mImageView = (ImageView) findViewById(R.id.iv_image);
mAdapter = new ChatMessage.ChatMessageAdapter(this, new ArrayList<ChatMessage>());
mListView.setAdapter(mAdapter);
buSpeak = (Button)findViewById(R.id.buSpeak);
CheckUserPermsions();
//chat button
mButtonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = mEditTextMessage.getText().toString();
//bot
String response = chat.multisentenceRespond(mEditTextMessage.getText().toString());
if (TextUtils.isEmpty(message)) {
return;
}
sendMessage(message);
mimicOtherMessage(response);
mEditTextMessage.setText("");
mListView.setSelection(mAdapter.getCount() - 1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null,null);
}else{
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null);
}
}
});
and the code for Using voice recognition, here the tts do not work
public void buSpeak(View view) {
startVoiceRecognitionActivity();
}
private void startVoiceRecognitionActivity() {
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);
//since you only want one, only request 1
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
startActivityForResult(intent, 1234);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK){
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
//pull all of the matches
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String topResult = matches.get(0);
EditText AutoText = (EditText) findViewById(R.id.et_message);
AutoText.setText(topResult);
String message = AutoText.getText().toString();
//bot
String response = chat.multisentenceRespond(AutoText.getText().toString());
if (TextUtils.isEmpty(response)) {
return;
}
sendMessage(message);
mimicOtherMessage(response);
AutoText.setText("");
mListView.setSelection(mAdapter.getCount() - 1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null,null);
}else{
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null);
}
}
}
public void CheckUserPermsions(){
if ( Build.VERSION.SDK_INT >= 23){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED ){
requestPermissions(new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return ;
}
}
}
//get acces to location permsion
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
// Permission Denied
Toast.makeText( this,"denail" , Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void onPause(){
if(tts !=null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
}
just call this method and pass your text in this method
public void textToSpeech(String message){
if (result==TextToSpeech.LANG_NOT_SUPPORTED ||result==TextToSpeech.LANG_MISSING_DATA){
Toast.makeText(Activity.this, "Language is Not Supported", Toast.LENGTH_SHORT).show();
}else {
String text=message;
if (text==null||text.equals("")){
text="Text is Empty";
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
} else {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
}
}
Okay I have solved the problem, Instead of onPause just used onDestry after tts.
and added tts.stop(); in buSpeak button method to stop tts when that button is pressed.
`Code below
public void buSpeak(View view) {
tts.stop();
startVoiceRecognitionActivity();
}
//after all other steps
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
I want to make an application in the way that when I speak, can answer me without the necessity of press any button. I want that my recordings guard on a string, and then depending of the record, the TTS can answer diferent things. This is my source code.
protected static final int RESULT_SPEACH =1;
private Button record, speak;
TextToSpeech t1;
String SpokedText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai);
record = (Button) findViewById(R.id.record);
speak = (Button) findViewById(R.id.speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reconize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
try {
startActivityForResult(reconize, RESULT_SPEACH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Your divece cannot execute this kind of operation", Toast.LENGTH_LONG);
t.show();
}
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode,resultCode,Data);
switch (requestCode) {
case RESULT_SPEACH: {
if (resultCode == RESULT_OK && null != Data) {
final String spoked = (RecognizerIntent.EXTRA_RESULTS);
if (spoked == "Good Morning") {
String SpokedText= "Good Morning";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
} else {
if (spoked== "I need your help") {
String SpokedText= "Alright sir";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.getDefault());
}
}
});
}}