在Android Ddevice中创建目录

时间:2018-01-11 16:28:13

标签: android file permissions

我在使用旧手机中的Android Studio创建目录时遇到问题(v 4.4.4),我尝试过更现代的手机,它有效,这是代码:

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "DIRECTORY";
    private Button click;

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

        setup();
    }

    private void setup() {
        click = findViewById(R.id.button);
        click.setOnClickListener(v -> getAlbumStorageDir(this, "samuel_es_dios"));
    }

    public void getAlbumStorageDir(Context context, String albumName) {

        pedirPermisos();
        // Get the directory for the app's private pictures directory.
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)+ "/"+ albumName);
        if (!file.mkdirs()) {
            Log.e(LOG_TAG, "Directory not created");
        }else {
            Log.e(LOG_TAG, "Directory created");
        }
    }

    private void pedirPermisos() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},50);
        }
    }
}

这就是Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="iam47662285.escoladeltreball.org.pruebasfile">

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


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

当它试图创建目录时它不会这样做,我不认为这是权限问题,我直接要求它们。知道发生了什么吗?

1 个答案:

答案 0 :(得分:0)

你必须指定它是哪种类型的视图所以

click = findviewbyid(R.id.button)

将其更改为

click=(Button)findviewbyid(R.id.button)