-1

I made a programme for uploading files to Mysql server and code is working fine but in Marshmallow device it not working and getting error for permission. this is my error..

05-17 21:13:13.783 32468-32468/com.example.dssandroid.myapplicationupload I/MainActivity: Selected File Path:/storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf
05-17 21:13:13.860 32468-32468/com.example.dssandroid.myapplicationupload I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@db75da1 time:94083612
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf: open failed: EACCES (Permission denied)
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:452)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:76)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err:     at com.example.dssandroid.myapplicationupload.MainActivity.uploadFile(MainActivity.java:147)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.

now i want to know how to ask user for access storage permission before running my. i am also giving my code so please help to resolve this issue...

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final int PICK_FILE_REQUEST = 1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private String selectedFilePath;
    private String SERVER_URL = "http://192.168.1.12:8080/uploadImage/uploadImage.php";
    ImageView resumeSelect;
    Button btnupload;
    TextView tvFileName;
    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resumeSelect = (ImageView)findViewById(R.id.attachment);
        btnupload = (Button)findViewById(R.id.upload);
        tvFileName = (TextView)findViewById(R.id.file_name);
        resumeSelect.setOnClickListener(this);
        btnupload.setOnClickListener(this);



    }

    @Override
    public void onClick(View v) {
        if(v== resumeSelect){

            //on attachment icon click
            showFileChooser();
        }
        if(v== btnupload){

            //on upload button Click
            if(selectedFilePath != null){
                dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //creating new thread to handle Http Operations
                        uploadFile(selectedFilePath);
                    }
                }).start();
            }else{
                Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        //sets the select file to all types of files
        intent.setType("*/*");
        //allows to select data and return it
        intent.setAction(Intent.ACTION_GET_CONTENT);
        //starts new activity to select file and return data
        startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == PICK_FILE_REQUEST){
                if(data == null){
                    //no data present
                    return;
                }


                Uri selectedFileUri = data.getData();
                selectedFilePath = FilePath.getPath(this,selectedFileUri);
                Log.i(TAG,"Selected File Path:" + selectedFilePath);

                if(selectedFilePath != null && !selectedFilePath.equals("")){
                    tvFileName.setText(selectedFilePath);
                }else{
                    Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //android upload file to server
    public int uploadFile(final String selectedFilePath){

        int serverResponseCode = 0;

        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";


        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);


        String[] parts = selectedFilePath.split("/");
        final String fileName = parts[parts.length-1];

        if (!selectedFile.isFile()){
            dialog.dismiss();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
                }
            });
            return 0;
        }else{
            try{
                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);


                //creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());

                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);

                //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                while (bytesRead > 0){
                    //write the bytes read from inputstream
                    dataOutputStream.write(buffer,0,bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable,maxBufferSize);
                    bytesRead = fileInputStream.read(buffer,0,bufferSize);
                }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();

                Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

                //response code of 200 indicates the server status OK
                if(serverResponseCode == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://192.168.1.101/uploadImage/upload/"+ fileName);
                            Toast.makeText(MainActivity.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //closing the input and output streams
                fileInputStream.close();
                dataOutputStream.flush();
                dataOutputStream.close();



            } catch (FileNotFoundException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
            }
            dialog.dismiss();
            return serverResponseCode;
        }

    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Praveen Gaur
  • 211
  • 3
  • 6
  • which permission you are using in you manifest.? write manifest.xml here. – Usman May 17 '17 at 16:04
  • i already give these permission for my project but when i testing in my Marshmallow android device it gives me error in blue lines that (.FileNotFoundException: /storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf: open failed: EACCES (Permission denied)) – Praveen Gaur May 17 '17 at 17:19
  • this code is working fine in kitkat android version. when i found this problem in my other device then i go through an article on stack overflow that in API level 19 and above you have to ask users for grant permission to access internal storage. i dont know about that's why i raise this question – Praveen Gaur May 17 '17 at 17:23

2 Answers2

1

In marshmallow 6.0.0 and above you need to use run time permissions.

This function checks permissions is granted or not?, also prompt permission that is required

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}
}

Check Permission result callback: if permission is granted or not

    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
    }
jagapathi
  • 1,635
  • 1
  • 19
  • 32
0

After the Android 6.0 Marshmallow google add restrict add permissions at runtime. see that link

add that line of code to your MainActivity in on create() Method.

     private ArrayList<Integer> listPermission;// add all permission in list which you used in manifes.xml
        listPermission = new ArrayList<>();
            listPermission.add(AISPermission.WRITE_EXTERNAL_STORAGE);
            listPermission.add(AISPermission.READ_CONTACTS);
            listPermission.add(AISPermission.SEND_SMS);
            listPermission.add(AISPermission.MICROPHONE);
PermissionUtils.requestPermission(context, listPermission, new PermissionUtils.OnRequestedPermissionListListener() {
                    @Override
                    public void onPermissionListResult(ArrayList<Integer> responsePermissionList, ArrayList<Boolean> isPermissionGrantedList) {
//                        if(isPermissionGrantedList.get())
                        for (int i = 0; i < responsePermissionList.size(); i++) {
                            if (responsePermissionList.get(i) != listPermission.get(i) || !isPermissionGrantedList.get(i)) {
                                return;
                            }
                        }
                        startActivity(new Intent(context, MainActivity.class));
                    }
                });
}
Usman
  • 339
  • 3
  • 15