Search code examples
javaandroidnullpointerexceptionwritefile

Android read/write local file (NullPointerException)?


I'm using simple code for read/write oneLine string to local file. And it works well, until I put Read/write_file_operations in another class. Now this code get null pointer exception, I think something wrong with Context, but I don't know what...

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import ru.true_code.android.jsonusingionlibrary.lib.RWfile;


public class MainActivity extends Activity {

    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.textView);
    }

    //Button write string to file
    public void btnWriteFile(View view) { 
        String data = "String for write to local file";
        RWfile rw = new RWfile();
        rw.writeToFile(data);
    }

    //Button read string from file and put it to textView
    public void brnReadFile(View view) {
        RWfile rw = new RWfile();
        tv1.setText(rw.readFromFile());
    }



}

class for read/write operations:

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


/**
 * Created by User on 04.02.2015.
 */
public class RWfile extends Activity {



    public void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }

    public String readFromFile() {

        String ret = "";

        try {
            InputStream inputStream = openFileInput("config.txt");

            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }

        return ret;
    }
}

Exception logcat:

02-04 09:11:50.938      479-479/ru.true_code.android.jsonusingionlibrary E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:2144)
            at android.view.View.performClick(View.java:2485)
            at android.view.View$PerformClick.run(View.java:9080)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:3683)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at android.view.View$1.onClick(View.java:2139)
            at android.view.View.performClick(View.java:2485)
            at android.view.View$PerformClick.run(View.java:9080)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:3683)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
            at ru.true_code.android.jsonusingionlibrary.lib.RWfile.writeToFile(RWfile.java:31)
            at ru.true_code.android.jsonusingionlibrary.MainActivity.btnWriteFile(MainActivity.java:27)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at android.view.View$1.onClick(View.java:2139)
            at android.view.View.performClick(View.java:2485)
            at android.view.View$PerformClick.run(View.java:9080)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:3683)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)

Solution

  • IllegalStateException: Could not execute method of the activity

    This Exception is occurring due to openFileOutput method call in RWfile class. because you are trying to call RWfile class method which is extending Activity class by creating object.

    To fix Exception do following :

    1. If RWfile is normal class then no need to extends Activity

    2. Add Context paramter in writeToFile method to access openFileOutput from Activity:

    public void writeToFile(String data,Context mContext) {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
             mContext.openFileOutput("config.txt", Context.MODE_PRIVATE));
    }
    

    Do same for readFromFile method because you are also calling openFileOutput in readFromFile method