简体   繁体   中英

Permission to save text in storage android not working

I have build sample app for user to write some text and save it on internal storage.

Format TXT or pdf. I have tried on android Kitkat sdk 19 and It's working fine but when I tried on the latest android 9 I got denied could not save the text in internal storage

Edit : I wonder If have to manually create My files folder

What I'm I missing ?

在此处输入图片说明

AndroidManifest

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

MainActivity

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

       mSaveTextBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            mText = mResultEt.getText().toString().trim();
            if(mText.isEmpty()){
                Toast.makeText(MainActivity.this, "write text First...", Toast.LENGTH_SHORT).show();
            }
            else{
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED){
                        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        requestPermissions(permissions,WRITE_EXTERNAL_STORAGE_CODE);
                    }else {
                        saveToTxtFile(mText);
                    }
                }else {
                    saveToTxtFile(mText);
                }
            }

        }
    }); 

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case WRITE_EXTERNAL_STORAGE_CODE: {
            if (grantResults.length > 0 && grantResults[0]
                    == PackageManager.PERMISSION_GRANTED) {
                //permission granted save data
                saveToTxtFile(mText);
            } else {
                //permission denied
                Toast.makeText(this, "Storage Permission required to store", Toast.LENGTH_SHORT).show();
            }
        }
        break;
    }
}

private void saveToTxtFile(String mText){
    //get current time for file name
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(System.currentTimeMillis());
    try{
        //path tp storage
        File path = Environment.getExternalStorageDirectory();
        //create folder named "My file"
        File dir = new File( path + "/My Files/");
        dir.mkdirs();
        //file name
        String fileName = "MyFile_" + timestamp + ".txt";

        File file = new File (dir, fileName);

        //used to store characater in file
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(mText);
        bw.close();

        //show file name and path where file saved
        Toast.makeText(this, fileName+"is saved to\n" +dir, Toast.LENGTH_SHORT).show();

    }catch (Exception e){
        //if anything goes wrong
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

As suggested both Shashanth and kashyap answers.

This is just a workaround but it works.

I have added

android:requestLegacyExternalStorage="true"

to my <application> element in the AndroidManifest.xml file.

And changed the line

File path = Environment.getExternalStorageDirectory();

to

File path = new File(getExternalFilesDir(null).getAbsolutePath());

In your MainActivity you should check if permission is granted or not, then use != operator.

if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED) {}

this line should be-

if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM