【问题标题】:Create directory in Android Ddevice在 Android 设备中创建目录
【发布时间】:2018-01-11 16:28:12
【问题描述】:

我在旧手机 (v 4.4.4) 中使用 Android Studio 创建目录时遇到问题,我在更现代的手机上尝试过,它可以工作,代码如下:

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);
        }
    }
}

这是清单:

<?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>

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

【问题讨论】:

  • 您的 logcat 中是否有任何指示错误的内容,如果有,请在此处发布
  • logcat没有报错,就是这个问题
  • problems creating directories with Android Studio ??? Android Studio 无法在 Android 设备上创建目录。我认为您的 Android 应用正在尝试这一点。
  • 也许你也需要 READ 权限。
  • if (!file.mkdirs())。错误的!你不应该盲目地总是调用 mkdirs()。仅当目录尚不存在时。检查 file.exists()。

标签: android file permissions


【解决方案1】:

你必须指定它是哪种类型的视图所以你已经完成了

click = findviewbyid(R.id.button)

改成

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

【讨论】:

  • 在新版本的 Android Studio 中你不需要这样做
猜你喜欢
  • 2023-03-09
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多