簡體   English   中英

寫入文件時出現空指針異常 - Android Studio

[英]Null Pointer Exception when writing to a File - Android Studio

每次我去發送傳感器收集的數據時,我的應用程序都會崩潰。 我給出的錯誤如下:

06-20 14:50:00.784  22983-22983/com.example.adam.proj2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.example.adam.proj2.SensorActivity.onClick(SensorActivity.java:124)
        at android.view.View.performClick(View.java:3549)
        at android.view.View$PerformClick.run(View.java:14393)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:4944)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

以下是收集傳感器數據的代碼:

 public void onSensorChanged(SensorEvent event) {
    float x = event.values[0];
    ArrayList<Float> enrolAcc = new ArrayList<>();
    ArrayList<Float> authAcc = new ArrayList<>();
    TextView textEnrol = (TextView) findViewById(R.id.textView);
    if (choice == 1) {
        mPreviousAcc = mCurrentAcc;
        mCurrentAcc = (float) Math.sqrt((double) (x * x));
        float delta = mCurrentAcc - mPreviousAcc;
        mDiffAcc = mDiffAcc * 0.9f + delta;
        if (enrolAcc.size() < 100) {
            enrolAcc.add(x);

        } else {
            enrolAcc.remove(0);
            enrolAcc.add(x);
        }
        walkData = enrolAcc.toString();
        textEnrol.setText(walkData);
    }

這是寫入文件的代碼(這發生在單擊按鈕時):

 public void onClick(View v) {
    switch (v.getId()) {
        case R.id.enrolBtn:
            choice = 1;
            Toast.makeText(this, "Enrolment Mode Selected", Toast.LENGTH_SHORT).show();
            break;
        case R.id.authBtn:
            choice = 2;
            Toast.makeText(this, "Authentication Service Starting", Toast.LENGTH_SHORT).show();
            break;
        case R.id.sendBtn:
            choice = 3;
            String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
            String fileName = "Walk Data.csv";
            String filePath = baseDir + File.separator + fileName;
            File f = new File(filePath);
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(f);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                out.write(walkData.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            android.net.Uri u1 = Uri.fromFile(f);
            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
            sendIntent.setType("text/html");
            startActivity(sendIntent);
            break;
    }
}

從我可以看出異常是由 out.write 方法生成的? 保存傳感器值的數組列表存儲在 walkData 字符串中,以便可以將該字符串寫入存儲在外部設備存儲器上的 csv 文件中。 我希望數據為 CSV 格式。

我很難過,無法弄清楚如何防止這種情況發生,任何幫助將不勝感激。

您收到錯誤是因為您正在嘗試寫入READ ONLY文件。
out = new FileOutputStream(f)拋出異常: java.io.FileNotFoundException: /storage/sdcard/Walk Data.csv: open failed: EROFS (Read-only file system) ,但您實際上忽略了它,所以out = NULL然后你會得到另一個異常。
將文件移動到可以寫入的位置 -

    String fileName = "Walk Data.csv";
    String baseDir = getFilesDir() + "/" + fileName;
    File f = new File(baseDir);

看代碼:

        try {
            out = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.write(walkData.getBytes());

在最后一行拋出異常。 那么,那條線上可能有什么問題呢?

out可能為空。 如果未找到文件, out將為空,因為您捕獲了該異常並假裝之前該行沒有發生任何錯誤,而將out保留為空。 你不應該嘗試使用out ,如果你只是無法初始化它。 try 塊應該包含所有使用out的行,而不僅僅是初始化它的行。

walkData也可以為空。 但由於我們不知道它來自哪里,我們不能說。 使用您的調試器知道哪個是空的。 不管答案是什么,修復你的異常處理代碼。 它應該看起來像

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);
            out.write(walkData.getBytes());

            android.net.Uri u1 = Uri.fromFile(f);
            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
            sendIntent.setType("text/html");
            startActivity(sendIntent);
        } catch (IOException e) {
            // TODO signal the error to the user. Printing a stack trace is not enough
        }
        finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO signal the error to the user. Printing a stack trace is not enough
                }
             }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM