Please can somebody help me I am really new to this.
Right now I have a firebase database with data the user added manually. I want an additional function that the user can scan the barcode and the barcode number will come up and they can enter the details this way and save it to the database. The next time they scan that item the fields will already be there.
This is the code I have for the barcode scanner. I want to add the fields to enter text into the result handler with the barcode number plus additional details being saved to the database.
Please can anybody help me I am so lost.
package com.virtual.fridge.BarcodeScanner;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.zxing.Result;
import com.virtual.fridge.Manifest;
import com.virtual.fridge.R;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;
/*SOURCE:
https://github.com/priyankapakhale/QRBarcodeScanner/blob/master/app/src/main/AndroidManifest.xml
https://www.youtube.com/watch?v=otkz5Cwdw38&t=3s
*/
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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
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());
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();
}
}
#Override
public void handleResult(me.dm7.barcodescanner.zbar.Result result) {
String result_text=result.getContents();
if(result_text!=null && !result_text.isEmpty()){
/* you can fetch your fields here and can write code to save in database here */
}
}
Related
Having issues uploading the name and URL into the Firebase Realtime Database. I am able to upload the images into Firebase Storage and everything else is working as intended. Really need the URL and metadata to move to the next phase of my project. Can someone please help me?
Attached are my codes below:
package com.example.x_raydetect;
import static android.content.ContentValues.TAG;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AlertDialogLayout;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class InsDB extends AppCompatActivity {
private Button mainPage, btnView, btnMed, btnGallery, btnInsert, btnCamera;
private EditText name;
private ImageView insertImageView;
private ProgressBar progressBar;
public Uri imageUri;
Bitmap bitmap;
private StorageReference StorageRef;
private DatabaseReference DatabaseRef;
private StorageTask UploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ins_database);
//menu tabs
mainPage = findViewById(R.id.mainPage);
btnView = findViewById(R.id.btnView);
btnMed = findViewById(R.id.btnMed);
//interface buttons/GUY
btnCamera = findViewById(R.id.btnCamera);
btnGallery = findViewById(R.id.btnGallery);
btnInsert = findViewById(R.id.btnInsert);
insertImageView = findViewById(R.id.insert_ImageView);
name = findViewById(R.id.name);
progressBar = findViewById(R.id.progressBar);
StorageRef = FirebaseStorage.getInstance().getReference("uploads");
DatabaseRef = FirebaseDatabase.getInstance("https://x-ray-detect-default-rtdb.asia-southeast1.firebasedatabase.app/").getReference("uploads");
mainPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainPage();
}
});
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openViewDB();
}
});
btnMed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGalleryChooser();
}
});
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 12);
}
});
btnInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UploadTask != null && UploadTask.isInProgress()) {
Toast.makeText(InsDB.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
insertFile();
}
}
});
}
private void openGalleryChooser() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void insertFile() {
if (imageUri != null) {
StorageReference fileReference = StorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
UploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, 500);
Toast.makeText(InsDB.this, "Upload successful", Toast.LENGTH_LONG).show();
/*
Upload upload = new Upload(name.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = DatabaseRef.push().getKey();
DatabaseRef.child(uploadId).setValue(upload);
*/
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//Log.d(TAG, "onSuccess: firebase download url: " + downloadUrl.toString()); //use if testing...don't need this line.
Upload upload = new Upload(name.getText().toString().trim(),downloadUrl.toString());
String uploadId = DatabaseRef.push().getKey();
DatabaseRef.child(uploadId).setValue(upload)
//ADDED NEW LISTENERS//
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
new AlertDialog.Builder(InsDB.this).setTitle("Success")
.setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
new AlertDialog.Builder(InsDB.this).setTitle("Failed")
.setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
})
.addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
new AlertDialog.Builder(InsDB.this)
.setTitle("Cancelled")
.setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
})
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
new AlertDialog.Builder(InsDB.this)
.setTitle("Complete")
.setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(InsDB.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot snapshot) {
double progress = (100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
public void openMainPage() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void openViewDB() {
Intent intent = new Intent(this, ViewDB.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && data != null) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(insertImageView);
} else if (requestCode == 12) {
if (data != null) {
bitmap = (Bitmap) data.getExtras().get("data");
insertImageView.setImageBitmap(bitmap);
}
}
}
}
I have read other posts on similar issue and follow their methods but it is still not working. Dependencies are correct and SHA-1/SHA-256 inserted into Firebase console. updated json report pasted in.
Thanks in advance for helping me!
The problem seems to be when using the following line of code:
while (!urlTask.isSuccessful());
If you add a semicolon at the end of the line, the while loop isn't executed. Besides that, a while loop without a body isn't helpful at all. So to solve this, you either use a while like this:
while (!urlTask.isSuccessful()) {
//Your logic
}
But in my opinion it makes more sense to use an if statement:
if(!urlTask.isSuccessful()) {
//Your logic
} else {
//Your logic
}
btnMed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String uploadId = DatabaseRef.push().getKey();
DatabaseRef.child(uploadId).setValue("test3").addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(InsDB.this, "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(InsDB.this, "Failure", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(InsDB.this, "Complete", Toast.LENGTH_SHORT).show();
}
}).addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
Toast.makeText(InsDB.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
});
new AlertDialog.Builder(InsDB.this).setMessage("Clicked").show();
}
});
I used this to test for response, however only the AlertDialog came out.
I am building an app that reads SMS's by converting them to speech.
After installing the apk it runs but when I close it and try to open it again it crashes.
It gives an error message saying the app keeps closing.
When I set it to only read after a button click it was working fine but after I changed it to read on initialization this problem came about.
Please help.
package com.example.receiver3;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
ListView listView;
Button btConvert, btNext;
private static final int PERMISSION_REQUEST_READ_CONTACTS = 100;
ArrayList<String> smsList;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
initializeTextToSpeech(); //edit
showContact();
}
else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
btConvert = findViewById(R.id.bt_stop);
btNext = findViewById(R.id.bt_next);
btConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get list value
for (String s : smsList) {
textToSpeech.stop();
}
}
});
Button button = (Button) findViewById(R.id.bt_next);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
});
}
private void initializeTextToSpeech() { //edit
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
}
}
});
}
public void openActivity(){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_READ_CONTACTS){
showContact();
initializeTextToSpeech(); //edit
}
else {
Toast.makeText(this, "Permission Required", Toast.LENGTH_SHORT).show();
}
}
private void showContact() {
Uri inboxUri = Uri.parse("content://sms/inbox");
smsList = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(inboxUri,null, null, null, null);
while (cursor.moveToNext()){
String number = cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
String body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
smsList.add("Number: "+number+ "\n" + "Body: "+body);
}
for (String s : smsList) {
textToSpeech.speak(s,TextToSpeech.QUEUE_ADD, null);
}
cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,smsList);
listView.setAdapter(adapter);
}
public void speak() { //edit
for (String s : smsList) {
textToSpeech.speak(s,TextToSpeech.QUEUE_ADD, null);
}
}
#Override
protected void onPause() { //edit
super.onPause();
textToSpeech.stop();
}
#Override
protected void onStop() {
super.onStop();
textToSpeech.stop();
}
#Override
protected void onResume() { //edit
super.onResume();
showContact();
initializeTextToSpeech();
}
}
You are now calling showContact() which in turn calls textToSpeech.speak() before initialising the textToSpeech object with textToSpeech = new TextToSpeech().
The code works fine on the first run because the user hasn't given the requested permission yet and showContact() doesn't get called.
You need to change your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
// *** MOVE THIS UP HERE. ***
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
return;
}
}
});
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContact();
return;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
btConvert = findViewById(R.id.bt_convert);
btNext = findViewById(R.id.bt_next);
btConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get list value
for (String s : smsList) {
textToSpeech.stop();
}
}
});
Button button = (Button) findViewById(R.id.bt_next);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
});
}
But that alone won't be enough as TTS isn't ready immediately. It's usable only after the onInit() callback has run and you receive the TextToSpeech.SUCCESS state there.
So, if you want to speak something as soon as possible at application startup then it needs to be triggered from onInit().
Maybe you can think of something like:
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
And then:
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContact();
}
}
}
});
I don't see why would you have the return; calls at all. And actually in the original code the return; exits the onCreate() before even trying to initialize the TTS if the permission is already given.
package com.infonium.password.ui.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDialog;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.infonium.password.events.CryptoEvent;
import com.infonium.password.events.DBExportEvent;
import com.infonium.password.runnable.DBExportRunnable;
import com.infonium.password.utils.AppConstants;
import com.infonium.password.utils.ResUtil;
import com.infonium.password.utils.UserDefault;
import com.kenumir.materialsettings.MaterialSettings;
import com.kenumir.materialsettings.items.CheckboxItem;
import com.kenumir.materialsettings.items.HeaderItem;
import com.kenumir.materialsettings.items.SwitcherItem;
import com.kenumir.materialsettings.items.TextItem;
import com.kenumir.materialsettings.storage.StorageInterface;
import de.greenrobot.event.EventBus;
import com.infonium.password.R;
import com.infonium.password.adapters.SettingsSpinnerAdapter;
import com.infonium.password.db.Account;
import com.infonium.password.db.AccountHelper;
import com.infonium.password.events.CryptoEvent;
import com.infonium.password.events.DBExportEvent;
import com.infonium.password.runnable.ChangePasswordRunnable;
import com.infonium.password.runnable.DBExportRunnable;
import com.infonium.password.ui.views.SelectorItem;
import com.infonium.password.utils.AppConstants;
import com.infonium.password.utils.CryptoUtil;
import com.infonium.password.utils.ResUtil;
import com.infonium.password.utils.UserDefault;
import static android.os.Build.VERSION_CODES.M;
import android.support.v7.widget.Toolbar;
/**
* Created by bob.sun on 16/6/21.
*/
public class SettingsActivity extends MaterialSettings {
public static final int RequestCodeSetMainPassword = 0x700;
private TextItem quickSwitcher;
private SelectorItem selectorItem;
private AppCompatDialog dialog;
private boolean didClickedChangeMaster;
private MaterialSettings ms;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.settings);
//ms = new MaterialSettings(this);
EventBus.getDefault().register(this);
addItem(new HeaderItem(this).setTitle(getString(R.string.security)));
addItem(new CheckboxItem(this, UserDefault.kNeedPasswordWhenLaunch).setTitle(getString(R.string.need_password_when_launch)).setOnCheckedChangeListener(new CheckboxItem.OnCheckedChangeListener() {
#Override
public void onCheckedChange(CheckboxItem cbi, boolean isChecked) {
UserDefault.getInstance(null).setNeedPasswordWhenLaunch(isChecked);
}
}));
String title = UserDefault.getInstance(null).hasQuickPassword() ? getString(R.string.disable_gesture_lock) : getString(R.string.enable_gesture_lock);
quickSwitcher = new TextItem(this, "quick_pass").setTitle(title).setOnclick(new TextItem.OnClickListener() {
#Override
public void onClick(TextItem textItem) {
if (UserDefault.getInstance(null).hasQuickPassword()) {
UserDefault.getInstance(null).clearQuickPassword();
quickSwitcher.updateTitle(getString(R.string.enable_gesture_lock));
} else {
Intent intent = new Intent(SettingsActivity.this, SetQuickPasswordActivity.class);
intent.putExtra("type", SetQuickPasswordActivity.ShowTypeSet);
startActivityForResult(intent, RequestCodeSetMainPassword);
}
}
});
addItem(quickSwitcher);
didClickedChangeMaster = false;
addItem(new TextItem(this, "change_password").setTitle(getString(R.string.change_master_password)).setOnclick(new TextItem.OnClickListener() {
#Override
public void onClick(TextItem textItem) {
didClickedChangeMaster = true;
startActivity(new Intent(SettingsActivity.this, AuthorizeActivity.class));
}
}));
addItem(new HeaderItem(this).setTitle(getString(R.string.puff_secure_keyboard)));
addItem(new TextItem(this, "ime").setTitle(getString(R.string.enable_puff_secure_keyboard)). setOnclick(new TextItem.OnClickListener() {
#Override
public void onClick(TextItem textItem) {
startActivity(new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS));
Toast.makeText(SettingsActivity.this, getString(R.string.please_enable_puf_ime), Toast.LENGTH_LONG).show();
}
}));
addItem(new HeaderItem(this).setTitle(getString(R.string.database)));
addItem(new TextItem(this, "database").setTitle(getString(R.string.export_database))
.setSubtitle(getString(com.infonium.password.R.string.database_file_can_be_used))
.setOnclick(new TextItem.OnClickListener() {
#Override
public void onClick(TextItem textItem) {
new AlertDialog.Builder(SettingsActivity.this).setTitle(getString(R.string.export_database))
.setMessage(com.infonium.password.R.string.confrim_export_database)
.setCancelable(false)
.setPositiveButton(com.infonium.password.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
d.dismiss();
dialog = ResUtil.getInstance(null).showProgressbar(SettingsActivity.this);
DBExportRunnable runnable = new DBExportRunnable(SettingsActivity.this);
new Thread(runnable).run();
}
})
.setNegativeButton(com.infonium.password.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}));
addItem(new HeaderItem(this).setTitle(getString(R.string.about)));
addItem(new TextItem(this, "about").setTitle(getResources().getString(R.string.about_puff_title)).setOnclick(new TextItem.OnClickListener() {
#Override
public void onClick(TextItem textItem) {
startActivity(new Intent(SettingsActivity.this, AboutActivity.class));
}
}));
}
#Override
public StorageInterface initStorageInterface() {
return UserDefault.getInstance(this);
}
#Override
public void onResume() {
super.onResume();
quickSwitcher.updateTitle(UserDefault.getInstance(null).hasQuickPassword()
? getString(R.string.disable_gesture_lock)
: getString(R.string.enable_gesture_lock));
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
public void onEventMainThread(Object event) {
// if (!(event instanceof DBExportEvent)) {
// return;
// }
if (event instanceof CryptoEvent && didClickedChangeMaster) {
didClickedChangeMaster = false;
if (((CryptoEvent) event).getType() == AppConstants.TYPE_MASTERPWD) {
Intent intent = new Intent(SettingsActivity.this, SetMasterPasswordActivity.class);
intent.putExtra("showMode", SetMasterPasswordActivity.ShowMode.ShowModeChange);
intent.putExtra("oldPassword", ((CryptoEvent) event).getResult());
UserDefault.getInstance(null).clearQuickPassword();
AccountHelper.getInstance(null).clearQuickAccount();
startActivity(intent);
}
return;
}
if (dialog != null) {
dialog.dismiss();
}
if (!(event instanceof DBExportEvent)) {
return;
}
DBExportEvent dbExportEvent = (DBExportEvent) event;
if (dbExportEvent.success) {
new AlertDialog.Builder(this)
.setTitle(R.string.success_em)
.setMessage(getString(R.string.database_exported_to)
+ dbExportEvent.filePath)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
} else {
new AlertDialog.Builder(this).setTitle(R.string.failed_em)
.setMessage(R.string.please_try_again)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != RequestCodeSetMainPassword ) {
return;
}
if (resultCode != RESULT_OK) {
UserDefault.getInstance(null).clearQuickPassword();
} else {
UserDefault.getInstance(null).setHasQuickPassword();
}
}
}
When i extend AppcompatActivity as a Super Class, error gets removed except addItem of MaterialSettings which is abstract class.
When i extend MaterialSettings as a Super Class, said error is generated.
I am designing an Settings Page in Android. Also tried javah in External Tools and also changed latest version to 28.+ and 27.1.1 for appcompact but still no error resolved.
Kindly guide me where and what i need to update or change.
Inheriting AppCompatActivity - Error Looks Like This
Inheriting MaterialSettings - Error Looks Like This
Material Settings is a 3rd party library which extends from ActionBarActivity. However, ActionBarActivity is deprecated and should not be used anymore. In order to support action bar in your activity, you should extend from AppCompatActivity.
I suggest do not use a 3rd party, unmaintained library for such a purpose. Instead, implement your own settings screen. If you do not know how to do that, you can find lots of tutorials online. Here is one for your reference: https://medium.com/#JakobUlbrich/building-a-settings-screen-for-android-part-1-5959aa49337c
When I run an AlertDialog asking the user to get a photo from the camera or the gallery the program doesn't seem to wait for the results and continues to execute. This causes the result to not get saved properly into the Image View field. Ignore the unused variables as I am not done coding this activity yet. I am new to this so any other criticism is appreciated.
package ca.android.whitehead.mycardswallet;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
public class AddEditCardActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etCardName;
private ImageView ivCardFront, ivCardBack, ivBarcode;
private Button btnCardFront, btnCardBack, btnBarcode;
private Bitmap image;
private static final int SELECT_PHOTO = 1;
private static final int CAPTUR_PHOTO = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_card);
etCardName = findViewById(R.id.etCardName);
ivCardFront = findViewById(R.id.ivCardFront);
ivCardBack = findViewById(R.id.ivCardBack);
ivBarcode = findViewById(R.id.ivBarcode);
btnCardFront = findViewById(R.id.btnCardFront);
btnCardBack = findViewById(R.id.btnCardBack);
btnBarcode = findViewById(R.id.btnBarcode);
btnCardFront.setOnClickListener(this);
btnCardBack.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btnCardFront:
getImage();
if (image != null)
{
ivCardFront.setImageBitmap(image);
}
break;
case R.id.btnCardBack:
getImage();
if (image != null)
{
ivCardBack.setImageBitmap(image);
}
break;
}
}
public void getImage()
{
AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCardActivity.this);
builder.setTitle("Pick from gallery or take new picture");
Toast.makeText(this, "In Get Image", Toast.LENGTH_SHORT).show();
builder.setItems(R.array.uploadImage, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case 0:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PHOTO);
break;
case 1:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTUR_PHOTO);
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
if (resultData != null) {
// this is the image selected by the user
Uri imageUri = resultData.getData();
if (imageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
if (requestCode == CAPTUR_PHOTO && resultCode == RESULT_OK) {
if (resultData != null) {
// this is the image selected by the user
image = (Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data");
}
}
}
}
I ended up taking CommonsWare advice.
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
public class AddEditCardActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etCardName;
private ImageView ivCardFront, ivCardBack, ivBarcode;
private Button btnCardFront, btnCardBack, btnBarcode;
private Bitmap image;
private static final int SELECT_PHOTO = 100;
private static final int CAPTURE_PHOTO = 200;
private static final int FRONT_IMAGE = 1;
private static final int BACK_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_card);
etCardName = findViewById(R.id.etCardName);
ivCardFront = findViewById(R.id.ivCardFront);
ivCardBack = findViewById(R.id.ivCardBack);
ivBarcode = findViewById(R.id.ivBarcode);
btnCardFront = findViewById(R.id.btnCardFront);
btnCardBack = findViewById(R.id.btnCardBack);
btnBarcode = findViewById(R.id.btnBarcode);
btnCardFront.setOnClickListener(this);
btnCardBack.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btnCardFront:
getImage(1);
break;
case R.id.btnCardBack:
getImage(2);
break;
}
}
public void getImage(final int image)
{
AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCardActivity.this);
builder.setTitle("Pick from gallery or take new picture");
Toast.makeText(this, "In Get Image", Toast.LENGTH_SHORT).show();
builder.setItems(R.array.uploadImage, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case 0:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PHOTO + image);
break;
case 1:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_PHOTO + image);
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void setBitmap(Uri imageUri, ImageView imageView)
{
if (imageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
imageView.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(resultCode == RESULT_OK) {
if (requestCode == (SELECT_PHOTO + FRONT_IMAGE)) {
if (resultData != null) {
setBitmap(resultData.getData(), ivCardFront);
}
}
else if (requestCode == (SELECT_PHOTO + BACK_IMAGE)) {
if (resultData != null) {
setBitmap(resultData.getData(), ivCardBack);
}
}
else if (requestCode == CAPTURE_PHOTO + FRONT_IMAGE) {
if (resultData != null) {
// this is the image selected by the user
ivCardFront.setImageBitmap((Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data"));
}
}
else if (requestCode == CAPTURE_PHOTO + BACK_IMAGE) {
if (resultData != null) {
// this is the image selected by the user
ivCardBack.setImageBitmap((Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data"));
}
}
}
}
}
I created a Flashlight app. It is working for all devices except marshmallow. Even after I used the asking for permission. I feel that there is something wrong in the asking for permission of my code. Do you see any problems?
package com.funny.flashlight;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final int REQUEST_CAMERA = 0;
ImageButton imageButton;
Camera camera;
Camera.Parameters parameters;
boolean isflash=false;
boolean isOn=false;
public void showCamera(View view)
{
if(checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED)
{
showCameraPreview();
}
else
{
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA))
{
Toast.makeText(this, "Camera Permission is needed to show Camera Preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_CAMERA);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode==REQUEST_CAMERA)
{
if (grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
showCameraPreview();
}
else {
Toast.makeText(this, "Permission was not Granted", Toast.LENGTH_SHORT).show();
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.imageButton);
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
camera = Camera.open();
parameters = camera.getParameters();
isflash = true;
}
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (isflash)
{
if (isOn)
{
imageButton.setImageResource(R.drawable.off);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isOn = false;
}
else
{
imageButton.setImageResource(R.drawable.on);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isOn = true;
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error");
builder.setMessage("FlashLight is not Available on this device");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onStop()
{
super.onStop();
if(camera!=null)
{
camera.release();
camera=null;
}
}
}
Depending on what you're trying to do, I would suggest following this format for checking/requesting permissions:
private int CAMERA_PERM = 0;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERM);
}
Then for retrieving the response:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case CAMERA_PERM: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission Granted
} else {
//Permission Denied
}
return;
}
}
}