I have created an app in which the user can take pics using their default camera.It works fine in older versions that is till lollipop but when i try to run the app in marshmallow the app gets closed.
So i have added some codes to give permission for the camera app by the user but even it is not working.
public class Cam extends Activity{
String receivingdata;
TextView namecat;
String amount,vat;
private static final String TAG = Cam.class.getSimpleName();
ImageButton imgview,imgchart,imgexit;
Boolean isInternetPresent = false;
ConnectionDetector cd;
AlertDialog alert;
ImageButton btgoback,btcaptureagain,btnpreview;
static TextView tv;
private ImageView imgPreview;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
public static Bitmap bitmap;
final Context context=this;
ConnectionClass connectionClass;
private static final String IMAGE_CAPTURE_FOLDER = "Receipt";
private static final int CAMERA_PIC_REQUEST = 1111;
private static File file;
private Uri ImagefileUri;
private static final String PREF_FIRSTLAUNCH_HELP = "helpcmaera";
private boolean helpDisplayed = false;
private static final String LOGIN_URL = "http://balajee2777-001-site1.1tempurl.com/backup-07032016/Receiptphp/receipts.php";
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Receipt");
alertDialogBuilder
.setMessage("Would you Like to go previous Page!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent i=new Intent(Cam.this,ListAct.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camcod);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
receivingdata = b.getString("key");
tv = (TextView)findViewById(R.id.camcodname);
tv.setText(receivingdata);
tv.setVisibility(View.INVISIBLE);
String[] bits=receivingdata.split("_");
String catname = bits[0];
String vatname= bits[1];
connectionClass= new ConnectionClass();
imgPreview = (ImageView) findViewById(R.id.imgpreview);
namecat=(TextView)findViewById(R.id.tvcatnamess);
namecat.setText(catname);
imgview=(ImageButton)findViewById(R.id.camlinearrecep);
imgchart=(ImageButton)findViewById(R.id.camlinearchart);
imgexit=(ImageButton)findViewById(R.id.camlinearexit);
btgoback=(ImageButton)findViewById(R.id.bgoback);
btnpreview=(ImageButton)findViewById(R.id.btnpreview);
btcaptureagain=(ImageButton)findViewById(R.id.bcaptureagain);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
showHelpForFirstLaunch();
btgoback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isInternetPresent) {
showreceipt();
}else{
neti();
}
}
});
btnpreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Cam.this,DeleteMainAct.class);
startActivity(i);
}
});
btcaptureagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to view receipts!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Viewreceipt.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgchart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to see report!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Chartboy.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CAMERA_PIC_REQUEST){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
Toast.makeText(this,"Camera permission not granted",Toast.LENGTH_SHORT).show();
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
private void showHelpForFirstLaunch() {
helpDisplayed = getPreferenceValue(PREF_FIRSTLAUNCH_HELP, false);
if (!helpDisplayed) {
showHelp();
savePreference(PREF_FIRSTLAUNCH_HELP, true);
}else if(helpDisplayed){
return;
}
}
private void showHelp() {
final View instructionsContainer = findViewById(R.id.container_help);
instructionsContainer.setVisibility(View.VISIBLE);
instructionsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
instructionsContainer.setVisibility(View.INVISIBLE);
}
});
}
private boolean getPreferenceValue(String key, boolean defaultValue) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(key, defaultValue);
}
private void savePreference(String key, boolean value) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private File getFile() {
String filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath, IMAGE_CAPTURE_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
String names=tv.getText().toString();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(file + File.separator + names+"_"+timeStamp
+ ".jpg");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
imgPreview.setVisibility(View.VISIBLE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
imgPreview.setImageBitmap(bmp);
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void neti() {
final LayoutInflater layoutInflater = LayoutInflater.from(Cam.this);
final View promptView = layoutInflater.inflate(R.layout.connectionlost, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false);
final Button retry=(Button)promptView.findViewById(R.id.btnretry);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=getIntent();
finish();
startActivity(intent);
}
});
alert= alertDialogBuilder.create();
alert.show();
}
private void showreceipt() {
LayoutInflater repcard=LayoutInflater.from(Cam.this);
View promptView=repcard.inflate(R.layout.moneyreceipt,null);
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(promptView);
final EditText amt=(EditText)promptView.findViewById(R.id.edamt);
final EditText vta=(EditText)promptView.findViewById(R.id.edvat);
final TextView tvs=(TextView)promptView.findViewById(R.id.tvamount);
final TextView tvat=(TextView)promptView.findViewById(R.id.tvvat);
tvs.setVisibility(View.INVISIBLE);
tvat.setVisibility(View.INVISIBLE);
amt.setRawInputType(Configuration.KEYBOARD_12KEY);
vta.setRawInputType(Configuration.KEYBOARD_12KEY);
final Button save=(Button)promptView.findViewById(R.id.btnmoneysave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tvs.setText(amt.getText().toString());
tvat.setText(vta.getText().toString());
amount=tvs.getText().toString();
vat=tvat.getText().toString();
// Toast.makeText(Cam.this, amount, Toast.LENGTH_LONG).show();
//Toast.makeText(Cam.this, vat, Toast.LENGTH_LONG).show();
detailsreceiptupload();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void detailsreceiptupload() {
String[] bits=receivingdata.split("_");
String catname = bits[0];
String cdte=bits[1];
String[] nyte=cdte.split("#");
String email=nyte[0];
String cdate=nyte[1];
String cimagetag=tv.getText().toString();
//String amt=tvs.getText().toString();
userLogin(catname, cdate,email,cimagetag,amount,vat);
}
private void userLogin(String catname, String cdate, String email, String cimagetag, String amount, String vat) {
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Cam.this, "Connecting to Cloud", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")) {
DoLogin dologin=new DoLogin();
dologin.execute("");
}
else
{
Toast.makeText(Cam.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("catname",params[0]);
data.put("cdate",params[1]);
data.put("email",params[2]);
data.put("cimagetag",params[3]);
data.put("amount",params[4]);
data.put("vat",params[5]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(catname,cdate,email,cimagetag,amount,vat);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DoLogin extends AsyncTask<String,String,String> {
String z="";
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
File destinationdir = new File(Environment.getExternalStorageDirectory() ,"/CompressedImage");
if (!destinationdir.exists()) {
destinationdir.mkdirs();
}
for(File file1:files){
FileOutputStream fos=null;
try{
File file=new File(destinationdir,file1.getName());
fos=new FileOutputStream(file);
Bitmap bm = BitmapFactory.decodeFile(file1.getAbsolutePath());
bm.compress(Bitmap.CompressFormat.JPEG, 25, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), destinationdir.getPath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
file.delete();
}
Intent i=new Intent(Cam.this,ReceiptGrid.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Cam.this.finish();
dismissDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}}
I have used an condition to check the phones version.If it is marshmallow then i have given a method name showcamera to do the functions for marshmallow
ShowCamera:
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
Related
public class DirectionActivity extends AppCompatActivity implements View.OnClickListener{
Button scanBtn;
TextView messageText, messageFormat, messageText2, messageFormat2, HTTPResult;
String Result = null;
QRResultData datum;
String myServer = "https://swulj.000webhostapp.com/bus_fetch.php";
String BUS_NUMBER= "EXTRA_BUS_NUMBER";
String Param = "PARAM";
String Stop = "STOP";
Context cntxt = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_direction);
scanBtn = findViewById(R.id.scanBtn);
messageText = findViewById(R.id.textContent);
messageFormat = findViewById(R.id.textFormat);
messageText2 = findViewById(R.id.textContent2);
messageFormat2 = findViewById(R.id.textFormat2);
HTTPResult = findViewById(R.id.HTTPResult);
// adding listener to the button
scanBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setPrompt("Scan a barcode or QR Code");
intentIntegrator.setOrientationLocked(true);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
// if the intentResult is null then
// toast a message as "cancelled"
if (intentResult != null) {
if (intentResult.getContents() == null) {
Toast.makeText(getBaseContext(), "Cancelled", Toast.LENGTH_SHORT).show();
} else {
// if the intentResult is not null we'll set
// the content and format of scan message
Result = intentResult.getContents();
datum = parseResult(Result, myServer);
showDialog(cntxt);
//messageText.setText(Result);
//messageFormat.setText(intentResult.getFormatName());
messageText.setText(datum.seatNumber);
messageFormat.setText(datum.busNumber);
messageText2.setText(datum.original);
messageFormat2.setText(Result);
//Toast.makeText(getApplicationContext(),"You download is resumed2",Toast.LENGTH_LONG).show();
HTTPConnection1 conn = new HTTPConnection1();
conn.execute(datum);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
public void showDialog(Context cntxt)
{
final CharSequence[] items = {"On-Direction", "Return-Direction"};
AlertDialog.Builder builder = new AlertDialog.Builder(cntxt);
builder.setTitle("Alert Dialog with ListView and Radio button");
//builder.setIcon(R.drawable.icon);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(cntxt, "Success", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(cntxt, "Fail", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public QRResultData parseResult(String Result, String urlArg)
{
QRResultData data = new QRResultData();
/*StringTokenizer multiTokenizer = new StringTokenizer(Result, ";");
if(multiTokenizer.hasMoreTokens())
{
data.busNumber = multiTokenizer.nextToken();
}
if(multiTokenizer.hasMoreTokens())
{
data.seatNumber = multiTokenizer.nextToken();
}*/
data.url = urlArg;
data.original = Result;
String[] split = Result.split(";");
data.busNumber = split[0];
if (split.length > 1) {
data.seatNumber = split[1];
}
return data;
}
.....
.....
I am trying to create a dialog. After the dialog shows, I should select on-direction or return-direction. If on-direction is selected, it should return true, if return-direction is selected, it should return false. But my dialog does not wait for user-inputs. It disappears after a moment.
I am trying to scan a barcode. after scanning the barcode, I am opening a dialog to get true or false. I will send the scanned result, boolean value to the HTTP SERVER.
so im making a chat app and my pictures are not showing now im using Picasso and android studio.
with i comment the code where the pictures are suppose to go everything works but if i leave the code in there i get this error java.lang.BootstrapMethodError: Exception from call site #4 bootstrap method
and the app crashes. i"m also connected to a firebase storage.
the logcat is here
java.lang.BootstrapMethodError: Exception from call site #4 bootstrap method
at okhttp3.internal.Util.<clinit>(Util.java:87)
at okhttp3.internal.Util.immutableList(Util.java:234)
at okhttp3.OkHttpClient.<clinit>(OkHttpClient.java:124)
at okhttp3.OkHttpClient$Builder.<init>(OkHttpClient.java:449)
at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:71)
at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:50)
at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:40)
at com.squareup.picasso.Picasso$Builder.build(Picasso.java:848)
at com.squareup.picasso.Picasso.get(Picasso.java:683)
at com.example.room.ProfileFragment$1.onDataChange(ProfileFragment.java:146)
avatarIv = view.findViewById(R.id.avatarIv);
nameTv = view.findViewById(R.id.nameTv);
emailTv =view.findViewById(R.id.emailTv);
phoneTv = view.findViewById(R.id.phoneTv);
coverIv = view.findViewById(R.id.coverIv);
fab = view.findViewById(R.id.fab);
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// until required data get
for (DataSnapshot ds : dataSnapshot.getChildren()){
//get data
String name = "" + ds.child("name").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String image = "" + ds.child("image").getValue();
String cover = "" + ds.child("cover").getValue();
//set data
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
Picasso.get().load(image).into(avatarIv);
}
catch (Exception e){
Picasso.get().load(R.drawable.ic_default_img_white).into(avatarIv);
}
try {
Picasso.get().load(cover).into(coverIv);
}
catch (Exception e){
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private void showEditProfileDialog() {
/* show dialog containg options
edit profile
cover photo
name
phone
* */
//options to show in dialog
String options [] = {"Edit Profile Picture ", "Edit Cover Photo ", "Edit Name ", "Edit Phone"};
// alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Action");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
profileorCoverPhoto = "image";
showImagePicDialog();
}else if (which==1){
// Edit cover click
profileorCoverPhoto = "cover";
showImagePicDialog();
}else if (which==2){
// Edit name click
showNamePhoneUpdateDialog("name");
}else if (which==3){
// Edit Phone click
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showImagePicDialog() {
String options [] = {"Camera", "Gallery"};
// alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Pick Image From ");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// camera clicked
if(!checkCameraPermission()){
reqCameraPermission();
}
else {
pickFromCamera();
}
showImagePicDialog();
} else if (which == 1) {
// Gallery cliked
if (!checkStoragePermission()){
reqStoragePermission();
}
else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(final String key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update" + key);
LinearLayout linearLayout =new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
final EditText editText= new EditText(getActivity());
editText.setHint("Enter" + key);
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//input text
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)){
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getActivity(), "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "" +e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(getActivity(), "please enter "+key, Toast.LENGTH_SHORT).show();
}
}
});
//add button to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0]== PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1]== PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
else {
Toast.makeText(getActivity(), "Please enable camera & storage permission ", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if (grantResults.length>0){
boolean writeStorageAccepted = grantResults[1]== PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
pickFromGallery();
}
else {
Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//this method will be called after picking image from cam or gallery
if (resultCode== RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(final Uri uri){
String filePathAndName = storagePath+ ""+ profileorCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask= taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
// check if image is uploaded or not
if (uriTask.isSuccessful()){
HashMap<String,Object> results = new HashMap<>();
results.put(profileorCoverPhoto,downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getActivity(), "Image Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error updating Image", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "some error occured", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//intent of picking image from device
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// intet to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
Intent galleryIntent= new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,IMAGE_PICK_GALLERY_CODE);
}
}
I'm trying to insert a barcode scanner in my ListFragment and use this tutorial: BarcodeScanner
But if I click on of the two buttons (QR or barcode-scan), it seems that my app doesn't find the downloaded XZing Barcode Scanner. But it is installed! I don't get an issue :-( ...
I think something is wrong in the try-part
Here is the code of my ListFragment:
private Button b1;
private Button b2;
static final String ACTION_SCAN = "com.google.xzing.client.android.SCAN";
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getView().findViewById(R.id.button_scan_barcode_ean);
b2 = (Button) getView().findViewById(R.id.button_scan_qr_code);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR(v);
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBar(v);
}
});
}
public void scanBar(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
public void scanQR(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
private static AlertDialog showDialog(final Activity act, CharSequence title,
CharSequence message,
CharSequence buttonYes,
CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == 0){
if (resultCode == Activity.RESULT_OK){
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(getActivity(), "Content:" + contents + "Format" + format, Toast.LENGTH_LONG);
toast.show();
final EditText editTextBarcode = (EditText) getView().findViewById(R.id.editText_barcode);
editTextBarcode.setText(contents);
}
}
}
Any ideas?
There is a typo in your ACTION_SCAN String. You wrote "xzing" instead of "zxing".
The correct String is
"com.google.zxing.client.android.SCAN"
I have a problem where I have to take an Image from the gallery and save it to the memory card after compressing it. I am able to pick the image from the gallery and even save it. But somehow there seems to be some coding mistake due to which I can not open the Image. Here is the code:
public class MainActivity extends Activity {
ImageView image;
Button save, add;
String fileName;
final Context context = this;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button)findViewById(R.id.buttonSave);
add = (Button)findViewById(R.id.buttonAdd);
image = (ImageView)findViewById(R.id.imageView);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.rename_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editRename);
alertDialogBuilder
.setTitle("Save Image")
.setMessage("Enter name")
.setNegativeButton("Save", new DialogInterface.OnClickListener() {
//
#Override
public void onClick(DialogInterface dialog, int which) {
fileName = userInput.getText().toString();
Log.d("Name" , fileName);
saveFile(null, fileName);
Toast.makeText(getApplicationContext(), "Image saved", Toast.LENGTH_SHORT).show();
}
})
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
Toast.makeText(getApplicationContext(), "Image save cancelled", Toast.LENGTH_SHORT).show();
}
});
AlertDialog build = alertDialogBuilder.create();
build.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void saveFile(Bitmap images, String fileName) {
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
File sdCard = Environment.getExternalStorageDirectory();
File pic = new File(sdCard , fileName + ".jpeg");
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(pic);
//bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
}
I have a picture that I can change.
I can choose a picture in my gallery or capture a photo.
When I capture a photo, I crop the image.
But the application takes time to crop my photo so I want to show a progressDialog.
My progressDialog appears on my application but it is hidden by the screen where I crop my photo.
How can I make the progressDialog appear inside the screen where I crop my photo ?
Sorry for my bad english...
My code :
public class FragmentMonCompte extends Fragment {
private ImageView ivAvatar;
// YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int CAPTURE_PICTURE = 0;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
// ADDED
private String filemanagerstring;
private Uri mCapturedImageURI;
ProgressDialog mProgressDialog = null;
boolean isPDShow;
Navigation navigation;
Intent data;
Bitmap photo;
Bundle extras;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_compte, container,
false);
ivAvatar = (ImageView) rootView.findViewById(R.id.iv_avatar);
ivAvatar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Navigation navigation = (Navigation) getActivity();
mProgressDialog = new ProgressDialog(navigation);
mProgressDialog.setMessage("Opération en cours...");
mProgressDialog.setTitle("Patientez");
final CharSequence[] items = {"Prendre une photo",
"Choisir une image", "Annuler"};
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
// set title
alertDialogBuilder.setTitle("Avatar :");
// set dialog message
alertDialogBuilder.setCancelable(false).setItems(items,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,
"");
mCapturedImageURI = navigation
.getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 170);
intent.putExtra("aspectY", 170);
intent.putExtra("outputX", 5000);
intent.putExtra("outputY", 5000);
startActivityForResult(Intent
.createChooser(intent,
"Appareil photo"),
CAPTURE_PICTURE);
}
if (item == 1) {
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 170);
intent.putExtra("aspectY", 170);
intent.putExtra("outputX", 5000);
intent.putExtra("outputY", 5000);
startActivityForResult(Intent
.createChooser(intent,
"Choisir une application"),
SELECT_PICTURE);
}
if (item == 2) {
dialog.cancel();
}
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// afficher
alertDialogBuilder.show();
}
});
return rootView;
}
/**
* Méthode qui permet d'ouvrir la gallery d'images ou l'appareil photo
*
* #param requestCode CAPTURE ou SELECT
* #param resultCode RESULT_OK or not
* #param data Intent
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Navigation navigation = (Navigation) getActivity();
this.navigation = navigation;
this.data = data;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAPTURE_PICTURE) {
isPDShow = true;
if( mProgressDialog!=null && !mProgressDialog.isShowing()) {
mProgressDialog.show();
}
new Thread() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
handler.sendEmptyMessage(0);
}
start();
}
};
Bitmap photo = null;
Bundle extras = data.getExtras();
new CapturePhotoAsyncTask().execute((Void) null);
}
if (requestCode == SELECT_PICTURE) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ivAvatar.setImageBitmap(photo);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if( mProgressDialog!=null & mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
/**
* Méthode qui retourne un bitmap compressé
*
* #param c Context de l'application
* #param uri Photo capturée
* #param requiredSize Taille requise
* #return Photo convertie en Bitmap
* #throws FileNotFoundException Fichier non trouvé
*/
public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize)
throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri),
null, o);
int widthTmp = o.outWidth, heightTmp = o.outHeight;
int scale = 1;
while (true) {
if (widthTmp / 2 < requiredSize || heightTmp / 2 < requiredSize) {
break;
}
widthTmp /= 2;
heightTmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(c.getContentResolver()
.openInputStream(uri), null, o2);
}
class CapturePhotoAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
ivAvatar.setImageBitmap(photo);
mProgressDialog.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
photo = decodeUri(navigation.getApplicationContext(),
mCapturedImageURI, 1000);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}//fin AsyncTask
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
new CapturePhotoAsyncTask().execute((Void) null);
isPDShow = false;
}
};
}
class CapturePhotoAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FragmentMonCompte.this);
pDialog.setMessage("Downloading data");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
ivAvatar.setImageBitmap(photo);
pDialog.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
photo = decodeUri(navigation.getApplicationContext(),
mCapturedImageURI, 1000);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}//fin AsyncTask