简体   繁体   中英

Can't getApplicationContext. because java.lang.NullPointerException

I want make mechanism that I can call from any place in app to write in file.

I make next class:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import android.content.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.content.Context;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LogFile  extends Activity {

    public void writeFile(String msg)
    {
        Log.d("writeFile", "writeToFile");

        try {
            Context context = getApplicationContext();
            FileOutputStream fos = context.openFileOutput("log.txt", Context.MODE_PRIVATE);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            BufferedWriter outputStream = new BufferedWriter(osw);
            outputStream.write(msg);
            outputStream.close();

        }  catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("writeFile", "File not found");
        } catch (NullPointerException e) {
            e.printStackTrace();
            Log.d("writeFile", "NullPointerException");
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("writeFile", "File problems");
        }
    }
} 

But in this line Context context = getApplicationContext(); I have error

W/System.err: java.lang.NullPointerException
 W/System.err:     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:185)
 W/System.err:     at com.example.tracklogger.LogFile.writeFile(LogFile.java:37)        

I'm not sure this is the "right" way to solve your problem or make it work. I think the problem is that you are passing the value of Activity's context (and this is null, for that reason it throws that Exception) and you need Application's context.

In my personal case, I solved a similar problem as follows:

GlobalVars.java file, containing all "global variables", like Applications context (not Activity's context):

public class GlobalVars extends Application {
public static Context context;

   @Override public void onCreate() {
      super.onCreate();
      context = getApplicationContext();
   }
}

Taken from here: Getting the Application Context

Good luck, and happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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