申请Permission / Android Studio

时间:2018-04-05 11:12:56

标签: javascript java android android-studio permissions

我正在使用Android应用程序将.txt写入存储。 但每次我想要权限(在运行时),应用程序崩溃与故障代码:"应用程序不幸停止..."。

权限在Manifest中定义,我会检查它是否已被授予。 但当它要求它时,应用程序立即崩溃。

希望有人可以帮助我。

这是我的代码:

public class MainActivity extends AppCompatActivity {
    //Deklarationen
    Button btn;
    EditText editText;

    //Ordner anlegen
    File ordner;

    //Mit beliebiger Zahl
    final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 22;

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

        //Zuweisungen Speicherort
        //ordner = new File(Environment.getExternalStorageDirectory(), "SD_Konfiguration");

        //Ordner erstellen wenn noch nicht da
        if(!ordner.exists())
        {
            //ordner.mkdirs(); //Abfragen ob bereits Permission
            if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            {
                createFolder();
            }
            else
            {
                //Dialog über Permission anzeigen
                ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
            }

        }
        else
        {
            Toast.makeText(getApplicationContext(), "Ordner bereits angelegt", Toast.LENGTH_SHORT).show();
        }

        //Listener
        editText = (EditText)findViewById(R.id.editText);
        btn = (Button)findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener()
        {
            //Aktiviert beim klicken
            @Override
            public void onClick(View v)
            {
                if (editText.getText().length() >0)
                {
                    //Datei anlegen
                    File Konfig = new File(ordner, "Konfig_Datei.txt");
                    Toast.makeText(getApplicationContext(), "Datei angelegt", Toast.LENGTH_SHORT).show();

                    //Schreiben
                    try
                    {
                        OutputStream outputStream = new FileOutputStream(Konfig);
                        outputStream.write(editText.getText().toString().getBytes());
                        outputStream.close();

                        //Wieder zurücksetzen
                        editText.setText(null);
                        Toast.makeText(getApplicationContext(), "Ergebnis gespeichert", Toast.LENGTH_SHORT).show();

                    }
                    catch (FileNotFoundException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Kein Text", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    //Ordner mit Permission anlegen
    private void createFolder()
    {
        File ordner = new File(Environment.getExternalStorageDirectory(), "SD_Konfiguration");
        ordner.mkdirs();
        Toast.makeText(getApplicationContext(), "Ordner angelegt", Toast.LENGTH_SHORT).show();
    }

    //Hier wird übergeben ob Permission bestätigt wurde (läuf alles zusammen)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            createFolder();
        }
    }
}

logcat的:

04-05 11:22:44.959 4986-4986/? D/AndroidRuntime: Shutting down VM
04-05 11:22:44.959 4986-4986/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.sidacon.sidaconsd, PID: 4986
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.sidacon.sidaconsd/de.sidacon.sidaconsd.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.exists()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.exists()' on a null object reference
    at de.sidacon.sidaconsd.MainActivity.onCreate(MainActivity.java:44)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

2 个答案:

答案 0 :(得分:0)

好的,首先要做的是,请求权限不要检查你的文件订阅者是否存在以获得许可。

if(!ordner.exists()) //Do that later. 

如果用户拒绝权限goBack / closeTheActivity

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

    if(requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
    {
        createFolder();
    }else{
        finish();
    }
}

答案 1 :(得分:0)

在存储权限首先授予权限之前,您正在检查文件是否存在,然后检查文件是否存在,如下所示。

        if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        {
            createFolder();
        }
        else
        {
            //Dialog über Permission anzeigen
            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
        }

    }

并像这样更改你的createFolder()

private void createFolder()
{
    File ordner = new File(Environment.getExternalStorageDirectory(), "SD_Konfiguration");
     if(!ordner.exists()){
    ordner.mkdirs();
    Toast.makeText(getApplicationContext(), "Ordner angelegt", Toast.LENGTH_SHORT).show();
    }
}