-1

In my Application I am uploading image and Status of an issue to an URL, Here my problem is When i updating the data it is working fine in lollipop version but in and other versions it is showing the updated records again and i click again my app is closing with unfortunately stopped Error. below is my code

        imageselect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(String.valueOf(PERMISSIONS))
                            != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},

                                MY_CAMERA_REQUEST_CODE);
                    }
                }else {

                    selectImage();
                }

            }

        });

And here is my code for Handling request Permisssions

 @Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == MY_CAMERA_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                selectImage();

            } else {

                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();

            }

        }
    }

Here is my code for Selecting Image:

private void selectImage() {

        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(Main3Activity.this);

        builder.setTitle("Add Photo!");

        builder.setItems(options, new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int item) {

                if (options[item].equals("Take Photo"))

                {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

                    startActivityForResult(intent,1);

                }

                else if (options[item].equals("Choose from Gallery"))

                {

                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(intent,2);

                }

                else if (options[item].equals("Cancel")) {

                    dialog.dismiss();

                }

            }

        });

        builder.show();
    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            if (requestCode == 1) {

                File f = new File(Environment.getExternalStorageDirectory().toString());

                for (File temp : f.listFiles()) {

                    if (temp.getName().equals("temp.jpg")) {

                        f = temp;
                        break;

                    }

                }

                try {

                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

                            bitmapOptions);

                    viewImage.setImageBitmap(bitmap);

                    OutputStream outFile = null;

                    File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()) + ".jpg");

                    try {

                        outFile = new FileOutputStream(file);

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);

                        outFile.flush();

                        outFile.close();

                    } catch (FileNotFoundException e) {

                        e.printStackTrace();

                    } catch (IOException e) {

                        e.printStackTrace();

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }

            } else if (requestCode == 2) {

                Uri selectedImage = data.getData();

                String[] filePath = { MediaStore.Images.Media.DATA };

                Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);

                c.moveToFirst();

                int columnIndex = c.getColumnIndex(filePath[0]);

                String picturePath = c.getString(columnIndex);

                c.close();

               // Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                bitmap = (BitmapFactory.decodeFile(picturePath));

                Log.w("path of image...****", picturePath+"");

                viewImage.setImageBitmap(bitmap);

            }

        }

    }

And the below code for services:

   btnupdate = (Button) findViewById(R.id.btnupdate);

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etupdate = ((EditText) findViewById(R.id.EditTextUpdate)).getText().toString();

                action = etupdate;
                ticketid = link;

                ImageUploadToServerFunction();

                    if (status.equalsIgnoreCase("Pending")) {

                        try {
                            action = URLEncoder.encode(action, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        try {
                            int l = etupdate.length();
                            if (l != 0) {
                                url = "http://182.18.169.39/trains/m/action.php?username=" + username + "&key=" + password + "&tktid=" + ticketid + "==&action=" + action+"&image_path="+ImagePath;
                            } else
                                url = "http://182.18.169.39/trains/m/action.php?username=" + username + "&key=" + password + "&tktid=" + ticketid + "==&action=";

                            HttpClient httpClient = new DefaultHttpClient();
                            HttpGet httpPost = new HttpGet(url);
                            HttpResponse response = httpClient.execute(httpPost);
                            HttpEntity entity = response.getEntity();

                            String responseString = EntityUtils.toString(entity);

                            JSONArray jsonarray = new JSONArray(responseString);
                            JSONObject jsonObj = new JSONObject();
                            jsonObj.put("Result", jsonarray);
                            String msg = jsonObj.getJSONArray("Result").getJSONObject(0).getString("Error");

                            String Successmsg = "Deficiency updated successfully.";

                            if (msg.equalsIgnoreCase(Successmsg)) {

                                onUpdatePressed(view);

                            } else {
                                Toast.makeText(getApplicationContext(), "failed to update", Toast.LENGTH_SHORT).show();

                            }
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Network Failed", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "Already updated you are not allow to update", Toast.LENGTH_SHORT).show();
                    }
                }
        });
    }

And finally this is my code for Upload Image

public void ImageUploadToServerFunction(){

        ByteArrayOutputStream byteArrayOutputStreamObject ;

        byteArrayOutputStreamObject = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);

        byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();

        final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);


        class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();
                progressDialog = ProgressDialog.show(Main3Activity.this,"Image is Uploading","Please Wait",false,false);
                    progressDialog.dismiss();
            }

            @Override
            protected void onPostExecute(String string1) {

                super.onPostExecute(string1);

                // Dismiss the progress dialog after done uploading.
                progressDialog.dismiss();

                // Printing uploading success message coming from server on android app.
               Toast.makeText(Main3Activity.this,string1,Toast.LENGTH_LONG).show();

                // Setting image as transparent after done uploading.
                viewImage.setImageResource(android.R.color.transparent);

            }

            @Override
            protected String doInBackground(Void... params) {

                ImageProcessClass imageProcessClass = new ImageProcessClass();

                HashMap<String,String> HashMapParams = new HashMap<String,String>();

                HashMapParams.put(ImagePath, ConvertImage);

                String FinalData = imageProcessClass.ImageHttpRequest(url, HashMapParams);

                return FinalData;
            }
        }
        AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();

        AsyncTaskUploadClassOBJ.execute();
    }

    public class ImageProcessClass{

        public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {

            StringBuilder stringBuilder = new StringBuilder();

            try {

                URL url;
                HttpURLConnection httpURLConnectionObject ;
                OutputStream OutPutStream;
                BufferedWriter bufferedWriterObject ;
                BufferedReader bufferedReaderObject ;
                int RC ;

                url = new URL(requestURL);

                httpURLConnectionObject = (HttpURLConnection) url.openConnection();

                httpURLConnectionObject.setReadTimeout(19000);

                httpURLConnectionObject.setConnectTimeout(19000);

                httpURLConnectionObject.setRequestMethod("POST");

                httpURLConnectionObject.setDoInput(true);

                httpURLConnectionObject.setDoOutput(true);

                OutPutStream = httpURLConnectionObject.getOutputStream();

                bufferedWriterObject = new BufferedWriter(

                        new OutputStreamWriter(OutPutStream, "UTF-8"));

                bufferedWriterObject.write(bufferedWriterDataFN(PData));

                bufferedWriterObject.flush();

                bufferedWriterObject.close();

                OutPutStream.close();

                RC = httpURLConnectionObject.getResponseCode();

                if (RC == HttpsURLConnection.HTTP_OK) {

                    bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));

                    stringBuilder = new StringBuilder();

                    String RC2;

                    while ((RC2 = bufferedReaderObject.readLine()) != null){

                        stringBuilder.append(RC2);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        }

        private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {

            StringBuilder stringBuilderObject;

            stringBuilderObject = new StringBuilder();

            for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {

                if (check)

                    check = false;
                else
                    stringBuilderObject.append("&");

                stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));

                stringBuilderObject.append("=");

                stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
            }

            return stringBuilderObject.toString();
        }

    }

This is for Go to previous Actvity

public void onUpdatePressed(View view) {

        Toast.makeText(Main3Activity.this, "Successfully Updated", Toast.LENGTH_SHORT).show();
        super.onBackPressed();

        Main2Activity m = new Main2Activity();
        m.loadHeroList();
    }

I Debug the code but I cant understand what happening, Help me any one to Solve m problem.

sathish
  • 1
  • 5
  • 1
    [maybe you should use FieProvider](https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed/38858040#38858040) – sanemars Mar 15 '18 at 07:21
  • add your PERMISSIONS value String – Erfan Mar 15 '18 at 07:25

1 Answers1

0
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ActivityCompat.checkSelfPermission(this, android.Manifest.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA != PackageManager.PERMISSION_GRANTED) {

                String[] PERMISSIONS = { Manifest.permission.CAMERA ,Manifest.permission.WRITE_EXTERNAL_STORAGE };

                    ActivityCompat.requestPermissions(this, PERMISSIONS , 10);
            }  else

            {


                //do your staff

            }

        }

        else
        {
            //Do your stuff here for SDK below 23

        }

and in Rsult :

   @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 10:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    //do your staff

                } else {

                    String[] PERMISSIONS = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE , android.Manifest.permission.CAMERA};

                    ActivityCompat.requestPermissions(this, PERMISSIONS , 10);

                }
                break;
        }
    }

replace above codes with yours

Erfan
  • 3,059
  • 3
  • 22
  • 49
  • I am able select an image and take a photo in all versions but At the time of uploading image is not uploading to the server.(other Than Lollipop) – sathish Mar 15 '18 at 08:32
  • that become your permissions define this permission in manifest to and replace above codes – Erfan Mar 15 '18 at 08:34