-2

I want to show my image in imageview after click but i don't know why this error occur and i searched a lot on this but i could no find solution of this problem and i tried to implement code after see solution but it doesn't work,so i m confused what's going wrong.This is my code:

package kmsg.com.onetouch.activity;

 public class UploadDocumentActivity extends AppCompatActivity {

JSONParser parser;
Bitmap photo;
ImageView mImgDocument;
Button mBtnBill,mBtnPres,mBtnGetFile,mBtnUpload;
EditText mEtBillDate,mEtbillValue,mEtStoreRefID,mEtDoctorID;
LinearLayout mBillLinear,mPresLinear;
String mBillDate,mBillValue,mStoreRefID,mDoctorID;
boolean flag= true;
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
File imageFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_document);
    parser = new JSONParser(this);

    init();

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
}

private void init() {
    mImgDocument=(ImageView)findViewById(R.id.imgDocument);
    mBtnBill=(Button)findViewById(R.id.btnBill);
    mBtnPres=(Button)findViewById(R.id.btnPres);
    mBtnGetFile=(Button)findViewById(R.id.btnGetFile);
    mBtnUpload=(Button)findViewById(R.id.btnUpload);
    mEtBillDate=(EditText)findViewById(R.id.et_billDate);
    mEtbillValue=(EditText)findViewById(R.id.et_billValue);
    mEtStoreRefID=(EditText)findViewById(R.id.et_refID);
    mEtDoctorID=(EditText)findViewById(R.id.et_doctorID);
    mBillLinear=(LinearLayout)findViewById(R.id.bill_linear);
    mPresLinear=(LinearLayout)findViewById(R.id.prescription_linear);
}

public void getBill(View view) {
    flag= true;
    mPresLinear.setVisibility(View.GONE);
    mBillLinear.setVisibility(View.VISIBLE);
}

public void getPrescription(View view) {
    flag=false;
    mBillLinear.setVisibility(View.GONE);
    mPresLinear.setVisibility(View.VISIBLE);
}

public void getFile(View view) {
    if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED){

        ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
                MY_CAMERA_PERMISSION_CODE);
    } else {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String pictureNm = getPictureName();
        imageFile = new File(pictureDirectory , pictureNm);
        Uri pictureUri = Uri.fromFile(imageFile);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
        cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);

    }
}

/* public void getFile(View view) {
    if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED){

        ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
                MY_CAMERA_PERMISSION_CODE);
    } else {


        Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File dir=
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pictureNm = getPictureName();

        File output=new File(dir, pictureNm);
        i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
        startActivityForResult(i, CAMERA_REQUEST);

    }
}

  */

private String  getPictureName(){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String timestamp = sdf.format(new Date());
    return "paymentProof" + timestamp + ".jpg";
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_CAMERA_PERMISSION_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            Intent cameraIntent = new
                    Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        } else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    if(resultCode != RESULT_CANCELED){
        if (requestCode == CAMERA_REQUEST) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            mImgDocument.setImageBitmap(photo);
        }
    }
}

private boolean validateFormForBill() {

    mBillDate = mEtBillDate.getText().toString().trim();
    mBillValue = mEtbillValue.getText().toString().trim();
    mStoreRefID = mEtStoreRefID.getText().toString().trim();
    mEtBillDate.setError(null);
    mEtbillValue.setError(null);
    mEtStoreRefID.setError(null);

    if (TextUtils.isEmpty(mBillDate.trim())) {
        mEtBillDate.setError("Bill Date cannot be blank");
        return false;
    }

    if (TextUtils.isEmpty(mBillValue.trim())) {
        mEtbillValue.setError("Bill Value cannot be blank");
        return false;
    }

    if (TextUtils.isEmpty(mStoreRefID.trim())) {
        mEtStoreRefID.setError("Ref ID cannot be blank");
        return false;
    }
    return true;
}

private boolean validateFormForPres() {


    mDoctorID = mEtDoctorID.getText().toString().trim();
    mEtDoctorID.setError(null);

    if (TextUtils.isEmpty(mDoctorID.trim())) {
        mEtDoctorID.setError("Doctor ID cannot be blank");
        return false;
    }
    return true;
}




public void uploadDocument(View view) {
    if (UtilityServices.checkInternetConnection(UploadDocumentActivity.this)) {
        if (flag) {
            if (UploadDocumentActivity.this.validateFormForBill()) {
                new UploadBill().execute();
            }
        } else {
            if (UploadDocumentActivity.this.validateFormForPres()) {
               // new UploadPres().execute();
            }
        }
    }else {
        Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
    }
}


private class UploadBill extends AsyncTask<String,String,String> {

    String status= null;
    String msg = null;
    JSONObject responseObject;
    @Override
    protected String doInBackground(String... strings) {
        List<Part> partList = new ArrayList<>();
        partList.add(new StringPart("billAmt", mBillValue));
        partList.add(new StringPart("billDate", mBillDate));
        partList.add(new StringPart("storeId", mStoreRefID));
        System.out.println("Data"+mBillDate+mBillValue+mStoreRefID);
        partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")));
       /* try {
            partList.add(new FilePart("file", imageFile));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        String url = Constants.UPLOAD_BILL;
        System.out.println("partList:"+partList);
        responseObject = parser.makeHttpRequestWithMultipart(url, partList);
        try {
            // Simulate network access.
            if (responseObject != null) {
                System.out.println("responseObject: " + responseObject.toString());
                try {
                    status = responseObject.getString(Constants.SVC_STATUS);
                    return status;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (responseObject.has(Constants.SVC_MSG)) {
                try {
                    msg = responseObject.getString(Constants.SVC_MSG);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return status;
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(final String success) {
        super.onPostExecute(success);

        if (success != null) {
            System.out.println(Constants.STATUS_SUCCESS);
            if (Constants.STATUS_SUCCESS.equals(success)) {
                System.out.println("Successful Svc Call:"+ "post object task details called");
                Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
            } else {
                System.out.println(success);
                try {
                    AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();

                    alertDialog.setTitle("Info");
                    alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
                    alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                }
                catch(Exception e)
                {
                    UtilityServices.appendLog("Show Dialog: "+e.getMessage());
                }
            }
        } else {
            System.out.println("svcstatus is null");
        }
    }
}
private class UploadPres extends AsyncTask<String,String,String> {

    String status= null;
    String msg = null;
    JSONObject responseObject;
    @Override
    protected String doInBackground(String... strings) {
        List<Part> partList = new ArrayList<>();
        partList.add(new StringPart("storeId", mDoctorID));
        partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")+""));
        try {
            partList.add(new FilePart("file", imageFile));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String url = Constants.UPLOAD_PRESCRIPTION;
        System.out.println("partList:"+partList);
        responseObject = parser.makeHttpRequestWithMultipart(url, partList);
        try {
            // Simulate network access.
            if (responseObject != null) {
                System.out.println("responseObject: " + responseObject.toString());
                try {
                    status = responseObject.getString(Constants.SVC_STATUS);
                    return status;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (responseObject.has(Constants.SVC_MSG)) {
                try {
                    msg = responseObject.getString(Constants.SVC_MSG);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return status;
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(final String success) {
        super.onPostExecute(success);

        if (success != null) {
            System.out.println(Constants.STATUS_SUCCESS);
            if (Constants.STATUS_SUCCESS.equals(success)) {
                System.out.println("Successful Svc Call:"+ "post object task details called");
                Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
            } else {
                System.out.println(success);
                try {
                    AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();

                    alertDialog.setTitle("Info");
                    alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
                    alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                }
                catch(Exception e)
                {
                    UtilityServices.appendLog("Show Dialog: "+e.getMessage());
                }
            }
        } else {
            System.out.println("svcstatus is null");
        }
    }
}
}

This is my class and i am trying to capture an image on click a button and then save into directory after that show into imageview and then want to send to server,i hope you will help me as a best programmer.

Gourav Manuja
  • 89
  • 1
  • 10

2 Answers2

0

this question may be a duplicate of this.

Basically, when you pass an OutPut file to the intent, you cannot read data from extra, you have to make sure that CameraApplication has access to your files. You are getting this exception, because CameraApplication cannot save the file on your directory, you need to add a file provider...

Please make your code is same as the base android documentation.

Anis BEN NSIR
  • 2,555
  • 20
  • 29
  • sir can you explain what should i do according to my code?? – Gourav Manuja Sep 21 '18 at 09:32
  • i would advice change the hole of your code based on the android documentation. I cannot help your because we have not access to hole project files. First of all, you have to choose, do you need the imageFile or just a thumbnail for your requirement. After that, restart from the beginning following the provided android tutorial. – Anis BEN NSIR Sep 21 '18 at 09:39
  • suppose i have an imageview and some image exist in that imageview,i want to send image to server using multipart,how do i do.how can i find path of that image which is in imageview and how can i send to server using multipart, i never use multipart so want to know – Gourav Manuja Sep 21 '18 at 10:12
  • so, for your requirement, you have to implement the saveFullSize, like explained hre (https://developer.android.com/training/camera/photobasics#TaskPath) after that your read the ImageData and show it on your ImageView. the next step it to send it to serer, this is a good link.(https://medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c). good luck. – Anis BEN NSIR Sep 21 '18 at 10:20
  • sir i am updating my class can u solute me after that? – Gourav Manuja Sep 21 '18 at 10:23
  • add a fileProvider like explained on the link into android developer tutorial, i have tried to create a chat room but you haven't 20 reputation... So i can just advise you to try to follow the tutorial step by step and understand it... Focus, on creating the image file, opening the camera, after that, try to read the file to show the image on ImageView and finally focus on sending file multipart... – Anis BEN NSIR Sep 21 '18 at 13:20
  • Thank you sir...but why should i need to use fileProvider @Anis – Gourav Manuja Sep 25 '18 at 04:51
-1

Try This

public void getFile(View view) {
    if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED){

        ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
                MY_CAMERA_PERMISSION_CODE);
    } else {
       
        
            Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File dir=
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    String pictureNm = getPictureName();

            File output=new File(dir, pictureNm);
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
            startActivityForResult(cameraIntent, CAMERA_REQUEST);

    }
}
Faiz Mir
  • 599
  • 5
  • 16