尝试写入文件时,Android应用程序崩溃

时间:2020-02-19 14:50:36

标签: android firebase firebase-realtime-database

我有一些数据并将其写入文件。但是我的应用程序一直崩溃。我尝试了很多事情,但是没有解决。

这是我的代码。

private void logInValidator(String userName, SimpleCallback<Boolean> finishedCallback) {

        DatabaseReference rootRef = databaseManager.getReference();
        DatabaseReference usersRef = rootRef.child("user");
        Query queryUsernameFinder = usersRef.orderByKey().equalTo(userName);
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    user = ds.getValue(User.class);
                }
                String passHash = null;
                passHash = Objects.requireNonNull(user).getPasswordHash();

                try {
                    validated = PasswordHandler.validatePassword(password, Objects.requireNonNull(passHash));
                } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                    e.printStackTrace();
                } finally {
                    finishedCallback.run(validated); // send the result to the callback
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                finishedCallback.run(false);
            }
        };
        queryUsernameFinder.addListenerForSingleValueEvent(valueEventListener);
    }

此代码查找我的数据库中是否存在用户名。

private void validateCredentials(){
        if (PermissionChecker.checkInternetPermission(this)) {
            if (!EmptyChecker.isEmpty(usernameTextInputLayout) && !EmptyChecker.isEmpty(passwordTextInputLayout)) {
                password = Objects.requireNonNull(passwordTextInputLayout.getEditText()).getText().toString();
                userName = Objects.requireNonNull(usernameTextInputLayout.getEditText()).getText().toString();
                logInValidator(userName, (success) -> {
                    if (success) {
                        String textToWrite = getTextToWrite();
                        writeToFile.write("UserData.txt",textToWrite);

                        //Intent mainIntent = new Intent(LogInActivity.this, MainActivity.class);
                        //startActivity(mainIntent);
                    } else {
                        showResult.setText(getString(userNotFound));
                    }
                });
            } else {
                showResult.setText(getString(string.emptyField));
            }
        } else
            PermissionChecker.requestInternetPermission(TestActivity.this,ContextGetter.getAppContext());
    }

此代码检查用户名和密码是否匹配。

public class WriteToFile extends AppCompatActivity {

    public void write(String fileName, String textToWrite) {
        //Checking the availability state of the External Storage.
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (PermissionChecker.checkInternetPermission(ContextGetter.getAppContext())) { 
                File dir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
                dir.mkdir(); // When application come this line app crashes
                File file = new File(dir, fileName);
                FileOutputStream os;
                try {
                    os = new FileOutputStream(file);
                    os.write(textToWrite.getBytes());
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                PermissionChecker.requestFilePermission(WriteToFile.this,ContextGetter.getAppContext()); // Code for permission
            }
        } else {
            Toast.makeText(ContextGetter.getAppContext(), "Can't write to File", Toast.LENGTH_SHORT).show();
        }
    }
}

此代码处理文件写入操作。我进行了调试以解决问题。我发现调试器进入“ dir.mkdir()”时,行应用程序崩溃。我认为这可能是由于同步问题引起的。但是我找不到或修复它。

这是我的logcat。

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.track.medicine, PID: 6098
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getExternalFilesDir(java.lang.String)' on a null object reference
        at android.content.ContextWrapper.getExternalFilesDir(ContextWrapper.java:249)
        at com.track.medicine.WriteToFile.write(WriteToFile.java:20)
        at com.track.medicine.TestActivity.lambda$validateCredentials$2$TestActivity(TestActivity.java:110)
        at com.track.medicine.-$$Lambda$TestActivity$RQ_IhdpryAE_sEsi6RtMvH3Py8Q.run(Unknown Source:4)
        at com.track.medicine.TestActivity$1.onDataChange(TestActivity.java:90)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.2.1:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

1 个答案:

答案 0 :(得分:1)

公共类WriteToFile扩展了AppCompatActivity {

公共无效写入

然后您致电writeToFile.write("UserData.txt",textToWrite);

似乎您已经使用new创建了一个活动实例。

那是不允许的活动。必须使用意图开始它们。

您的扩展活动类不能像public void write那样拥有公共成员。