I have implemented Barcode Scanner functionality in my application using ZBarScannerView.
I have an activity which contains multiple fragments and on one fragment I have a scan button. By clicking on that button I jump to scan activity where I have implemented the ZBarScannerView code.
When I got the barcode from scan activity I jumped it back to that fragment which contains the barcode click button. And then if I press back from that fragment it shows blank screen. What should I do?
Please Reply
Code for ScanActivity:
public class ScanActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private static final int REQUEST_CAMERA = 1;
ArrayList<ModelProductDetail> modelProductArticleCodeList;
DatabaseHelper databaseHelper;
String article_code;
ArrayList<ModelUnrecognisedCode> modelUnrecognisedCodeArrayList;
ArrayList<ModelUnrecognisedCode> singleUnrecognisedCheck;
//camera permission is needed.
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
databaseHelper = new DatabaseHelper(this);
checkUserPermission();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void checkUserPermission() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
return;
}
}
loadImage();
}
private void loadImage() {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
}
#Override
public void onResume() {
super.onResume();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.startCamera();
mScannerView.setResultHandler(this);
// Stop camera on pause
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.stopCamera(); // Stop camera on pause
}
}
#Override
public void handleResult(me.dm7.barcodescanner.zbar.Result result) {
String resultCode = result.getContents();
Log.e("TAG", "handleResult: " + resultCode);
mScannerView.stopCamera();
modelProductArticleCodeList = new ArrayList<>();
modelProductArticleCodeList = databaseHelper.getProductByArtCode(resultCode);
if (modelProductArticleCodeList.size() == 0) {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(getApplicationContext().VIBRATOR_SERVICE);
vibrator.vibrate(1000);
singleUnrecognisedCheck = new ArrayList<>();
singleUnrecognisedCheck = databaseHelper.getUnrecognisedByCode(resultCode);
if (singleUnrecognisedCheck.size() == 0) {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("unrecognised_alert", true);
in.putExtra("unrecognised_code", resultCode);
in.putExtra("jump", "1");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "not matched code", Toast.LENGTH_SHORT).show();
} else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("jump", "3");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "Unrecognised code has already been added.", Toast.LENGTH_SHORT).show();
}
} else {
// for (ModelProductDetail modelProductDetail : modelProductArticleCodeList) {
// article_code = modelProductDetail.getArticle_code();
// }
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
public void changeFragments(Fragment fragment) {
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void getDialog() {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_unrecognised_code);
d.setCanceledOnTouchOutside(true);
d.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
final EditText etCode = (EditText) d.findViewById(R.id.etCode);
final EditText etrecognisedComment = (EditText) d.findViewById(R.id.etrecognisedComment);
ImageView imgClose = (ImageView) d.findViewById(R.id.imgClose);
ImageButton ibSubmit = (ImageButton) d.findViewById(R.id.ibSubmit);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ModelUnrecognisedCode modelUnrecognisedCode = new ModelUnrecognisedCode();
modelUnrecognisedCode.setUnrecognised_code(etCode.getText().toString());
modelUnrecognisedCode.setUnrecognised_comment(etrecognisedComment.getText().toString());
databaseHelper.addUnrecognisedCode(modelUnrecognisedCode);
// changeFragments(new SearchProductFragment());
modelUnrecognisedCodeArrayList = new ArrayList<>();
modelUnrecognisedCodeArrayList = databaseHelper.getUnrecognisedCode();
Log.e("TAG", "unrecognised code: " + modelUnrecognisedCodeArrayList.size());
d.dismiss();
}
});
d.show();
}
}
I'm assuming After successful barcode scanning you're fetching product data and if data found then you are changing the screen . So change your else statement with this and see if it works
else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
startActivity(in);
finish();
}
Related
The permission dialog does not show up on Android 9 and below. My code works fine on Android 11. i've tried ActivityCompat.requestPermissions() and ActivityResultLauncher but none of them work.
When it runs the line permissionResultLauncher.launch() my app crashes and it also crashes the emulator, such that i have to delete the Emulator and reinstall a new one, otherwise it won't show me anything on the screen.
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
...
</application>
public class MainActivity extends AppCompatActivity{
private ActivityMainBinding binding;
private long pressedTime;
private ActivityResultLauncher<String[]> permissionResultLauncher;
private boolean isRecordPermGranted = false;
private boolean isWritePermGranted = false;
private int totalCount;
private DBHelper dbHelper;
private ImageButton imgbtnRecord, imgbtnList;
private ImageView ivRestore;
private TextView tvLoading, tvRecord;
private boolean asyncTaskRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);
if(totalCount < 4){
totalCount++;
editor.putInt("counter", totalCount);
editor.commit();
}
dbHelper = new DBHelper(this);
asyncTaskRunning = false;
imgbtnRecord = (ImageButton) findViewById(R.id.imgbtnRecord);
imgbtnList = (ImageButton) findViewById(R.id.imgbtnList);
tvLoading = findViewById(R.id.tvLoading);
tvRecord = findViewById(R.id.tvRecord);
ivRestore = findViewById(R.id.ivRestore);
tvLoading.setVisibility(View.GONE);
ivRestore.setVisibility(View.GONE);
imgbtnRecord.setVisibility(View.VISIBLE);
imgbtnList.setVisibility(View.VISIBLE);
tvRecord.setVisibility(View.VISIBLE);
isRecordPermGranted = ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
isWritePermGranted = ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
permissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
#Override
public void onActivityResult(Map<String, Boolean> result) {
if(result.get(Manifest.permission.RECORD_AUDIO)!= null){
isRecordPermGranted = result.get(Manifest.permission.RECORD_AUDIO);
Log.d("3","-------------------------" + isRecordPermGranted);
}
if(result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= null){
isWritePermGranted = result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.d("4","-------------------------" + isWritePermGranted);
}
if(isWritePermGranted == false || isRecordPermGranted == false){
if(totalCount <3){
finishAffinity();
}else{
Intent intent = new Intent( MainActivity.this, PermissionActivity.class);
startActivity(intent);
}
}
}
});
imgbtnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isRecordPermGranted == false){
requestPermission();
}else{
openRecordingActivity();
}
}
});
imgbtnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isRecordPermGranted || !isWritePermGranted){
requestPermission();
}else{
openRecordingsListActivity();
}
}
});
}
public void openRecordingsListActivity() {
Intent intent = new Intent(this, RecordingsListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void openRecordingActivity(){
Intent intent = new Intent(this, RecordingActivity.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
if(pressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}else{
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
}
pressedTime = System.currentTimeMillis();
}
public void requestPermission(){
List<String> permissionRequests = new ArrayList<>();
if(!isRecordPermGranted && !isWritePermGranted){
permissionRequests.add(Manifest.permission.RECORD_AUDIO);
permissionRequests.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}else if(!isRecordPermGranted){
permissionRequests.add(Manifest.permission.RECORD_AUDIO);
}else if(!isWritePermGranted){
permissionRequests.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
Log.d("permissionRequests list", permissionRequests.toString());
if(!permissionRequests.isEmpty()){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
boolean shouldShowRationale = false;
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ){
shouldShowRationale = true;
Log.d("1","-------------------------");
}
if( ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)){
shouldShowRationale = true;
Log.d("2","-------------------------");
}
if(shouldShowRationale){
Toast.makeText(this, "Permissions Needed!", Toast.LENGTH_SHORT).show();
Log.d("5","-------------------------");
}else{
permissionResultLauncher.launch(permissionRequests.toArray(new String[0]));
Log.d("6","-------------------------");
}
}else{
Log.d("old permission ", permissionRequests.toArray(new String[permissionRequests.size()])+" " );
ActivityCompat.requestPermissions(MainActivity.this,permissionRequests.toArray(new String[permissionRequests.size()]), 5);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 5){
for (int i =0; i< permissions.length; i++){
if(permissions[i].equals(Manifest.permission.RECORD_AUDIO) && grantResults[i] != PackageManager.PERMISSION_GRANTED){
isRecordPermGranted = false;
}
if(permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] != PackageManager.PERMISSION_GRANTED){
isWritePermGranted = false;
}
}
}
if(isWritePermGranted == false || isRecordPermGranted == false){
Log.d("REQUEST PERMISSIONS RESULT", "onPermissionResult");
if(totalCount <3){
finishAffinity();
}else{
Intent intent = new Intent( MainActivity.this, PermissionActivity.class);
startActivity(intent);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
When i use the statement if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO )
then it runs the first part of the "OR" statement and shows one of the permission dialog but it never shows both, even with an "&&" or my current code in the requestPermission()
i've tried it without shouldShowRequestPermissionRationale, but it still doesn't work.
I've also added the permissions in the AndroidManifest file.
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();
}
on my app I have implemented a control permission for Android 6 and 7.
When app run show splash screen with message and after permission start the main activity. On Android 6 and 7 works fine but on Android 19 / 20 when i run app appear the message but the app remain blocked on splash screen and don't start main activity.
this is my code:
public class splashscreen extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient googleApiClient;
private Location myLocation;
private static final int MY_PERMISSIONS_REQUEST_GET_ACCOUNTS = 1;
private SparseIntArray mErrorString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mErrorString = new SparseIntArray();
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int code = api.isGooglePlayServicesAvailable(this);
if (code != ConnectionResult.SUCCESS)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Attenzione");
alert.setMessage("Google Play Services non installati o non aggiornati!");
alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
finish();
}
});
alert.show();
}
// Create an instance of GoogleAPIClient.
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
// Permessi
public void onPermissionsGranted(int requestCode) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
}
public void requestAppPermissions(final String[]requestedPermissions, final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean showRequestPermissions = false;
for(String permission: requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
if(showRequestPermissions) {
Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(splashscreen.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionsGranted(requestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
Intent i = new Intent(splashscreen.this, MainActivity.class); //start activity
splashscreen.this.startActivity(i);
} else {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
/*Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
}).show();*/
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onConnected(Bundle connectionHint) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
myLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
if (isFirstStart) {
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(splashscreen.this).create();
alertDialog.setTitle(getResources().getString(R.string.titolo_intro_sms));
alertDialog.setMessage(getResources().getString(R.string.intro_sms));
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(splashscreen.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
//Intent i = new Intent(splashscreen.this, MainActivity.class);
//startActivity(i);
}
});
alertDialog.show();
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("firstStart", false);
e.apply();
} else {
startApp();
}
}
private void startApp() {
if(googleApiClient != null) {
googleApiClient.disconnect();
}
startActivity(new Intent(splashscreen.this, MainActivity.class));
finish();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
That happens because you are not starting the Activity if permissions are granted without requesting them. Before api 23 this check fails:
if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
// Not called before api 23 unless the permissions are not specified in the manifest.
}
So you have to modify your method onPermissionsGranted() as follow:
public void onPermissionsGranted(int requestCode) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
// Start the Activity if permissions are granted.
startActivity(new Intent(this, MainActivity.class));
}
Hi I am new for android and in my app I am using Z-bar library for scanning barcode.
For this I am using ZbarScannerActivity class like below, so after scanning the barcode I am getting those barcode results where ever I want using onActivityResult method.
Here my problem is when I am scanning the barcode I want to get this result in my Fragment, but here onActivityResult not calling in my Fragment.
But it's calling in my Activities please help me.
How can I solve this problem?
ZbarScanner Activity:-
public class ZBarScannerActivity extends ActionBarActivity {
private Camera mCamera;
private CameraPreview mPreview;
private Handler autoFocusHandler;
ImageScanner scanner;
ImageView backButton;
private boolean barcodeScanned = false;
private boolean previewing = true;
CustomTextview navigation_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner_view_layout);
ActionBar actionBar = getSupportActionBar();
String header = "<font color=\"#ffffff\">" + "BarCode Scanner"
+ " </font>";
CommonUtils.actionbarHeader(this, actionBar, header);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
autoFocusHandler = new Handler();
mCamera = getCameraInstance();
/* Instance barcode scanner */
scanner = new ImageScanner();
scanner.setConfig(0, Config.X_DENSITY, 3);
scanner.setConfig(0, Config.Y_DENSITY, 3);
mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
preview.addView(mPreview);
navigation_title = (CustomTextview)findViewById(R.id.navigationTitle_id);
navigation_title.setText("Barcode Scanner");
backButton = (ImageView)findViewById(R.id.navigationbackbutton_id);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static {
System.loadLibrary("iconv");
}
public void onPause() {
super.onPause();
releaseCamera();
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
private void releaseCamera() {
if (mCamera != null) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
private Runnable doAutoFocus = new Runnable() {
public void run() {
if (previewing)
mCamera.autoFocus(autoFocusCB);
}
};
PreviewCallback previewCb = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = scanner.scanImage(barcode);
if (result != 0) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
SymbolSet syms = scanner.getResults();
for (Symbol sym : syms) {
System.out.println("------->"+sym.getData());
barcodeScanned = true;
finishActivivtyWithResult(sym.getData());
}
}
}
};
// Mimic continuous auto-focusing
AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
autoFocusHandler.postDelayed(doAutoFocus, 1000);
}
};
/**
*
* #param barCodeResult
*/
private void finishActivivtyWithResult(String barCodeResult){
if (barCodeResult.contains("//b")) {
String replacedString = barCodeResult.replace("//b", "");
System.out.println("One========>" + replacedString);
barCodeResult = replacedString;
}
if (barCodeResult.contains("/t")) {
String replacedString = barCodeResult.replace("/t", "-");
System.out.println("After========>" + replacedString);
barCodeResult = replacedString;
}
Bundle conData = new Bundle();
conData.putString("barCodeResult", barCodeResult);
Intent intent = new Intent();
intent.putExtras(conData);
setResult(RESULT_OK, intent);
finish();
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
my fragment:-
//Camera Button Action Event:-
/**
* #return
*/
private View.OnClickListener cameraDetails() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
BAR_CODE_SCANNER_CODE = 100;
checkCameraPermission();
}
};
}
//BarCode Scanner Result:-
private void checkCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkManifestPermissionSets();
} else {
scanProductCode();
}
}
#TargetApi(23)
private void checkManifestPermissionSets() {
int cameraPermission = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA);
List<String> permissions = new ArrayList<String>();
if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (!permissions.isEmpty()) {
requestPermissions(
permissions.toArray(new String[permissions.size()]),
REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
} else {
scanProductCode();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
//Log.d("Permissions", "Permission Granted: "+ permissions[i]);
scanProductCode();
break;
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
//Log.d("Permissions", "Permission Denied: " + permissions[i]);
//CommonUtils.showToastMessage(StockTransfer.this, "You've disabled the App required Permissions");
break;
}
}
}
break;
default: {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
}
private void scanProductCode() {
if (isCameraAvailable()) {
CommonUtils.showToastMessage(getActivity(),
"Please Scan Your Product BarCode");
callThreadScannerActivity();
} else {
Toast.makeText(getActivity(), "Rear Facing Camera Unavailable",
Toast.LENGTH_SHORT).show();
}
}
private void callThreadScannerActivity() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// dialog.dismiss();
callScannerActivity();
}
}, 700);
}
// Call Scanner Activity:-
private void callScannerActivity() {
Intent intent = new Intent(getActivity(), ZBarScannerActivity.class);
startActivityForResult(intent, BAR_CODE_SCANNER_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("result code------>" + requestCode);
}
private boolean isCameraAvailable() {
PackageManager pm = getActivity().getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
}
Simple logic connected to general life
activity : father(parent)
fragment : child
if child wanna money than he ask to him/ her father.
technical way if fragment(child) wanna data from onActivityResult it always VIA Activity(father).
ohk .. lets look on code side
stuff at
yourActivity (Parent)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
this list of fragment(child) of activity said to him activity(father) for data
when activity received data it gives as fragments(childs) demands.
In fragment whenever we start activity for any result then that result in received in onActivityResult of activity then we have to pass this result to fragment's onActivityResult
Write this to your activitys's onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logg.e("RESULT ", " " + resultCode);
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case 100:
Fragment YourRfargment= getFragmentManager().findFragmentByTag("Your Fragment TAG");
updateproFragment.onActivityResult(requestCode, resultCode, data);
break;
}
}
by this you will get your result in fragment's onActivityresult.