简体   繁体   English

要求权限时,应用崩溃/ Android Studio

[英]App Crashes when asking for Permission / Android Studio

i am working on a Android App for writing .txt to the storage at the moment. 我目前正在使用Android应用程序将.txt写入存储。 But everytime i want to aks for Permissions (in Runtime), the App Crashes with fault Code: "App unfortunality stopped...". 但是每当我想请求权限(在运行时)时,应用程序都会崩溃,并显示错误代码:“应用程序不幸停止...”。

Permission is defined in Manifest, and i do checking if its already granted. 权限是在清单中定义的,我会检查它是否已被授予。 But when its going to ask for it the App crashes immediatly. 但是当它要它时,应用程序立即崩溃。

Hope somebody can help me. 希望有人能帮助我。

Here is my Code: 这是我的代码:

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: 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) 

Ok, first thing you do is, ask for permissions don't check for your File ordner's existence for asking permission. 好的,您要做的第一件事是,请求权限不要检查文件ordner是否存在请求权限。

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

And if user denies the permission goBack / closeTheActivity 如果用户拒绝权限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();
    }
}

You are checking file exists or not before storage permission first give permission and then check file exists like below. 您正在检查文件是否存在,然后再授予存储权限,然后再如下所示检查文件是否存在。

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

    }

and change your createFolder() like this 并像这样更改您的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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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