Search code examples
androidfile-ioandroid-contentprovider

getContext() returns Null


I am using getContext() method in Android to get the Context and then create files. But, I consistently get a null pointer exception when the app is invoked from a crash, and then getContext() is accessed.

Below is my code which invokes after the crash. This code works fine before the crash but fails after the crash.

synchronized public void insertR(String filename,String content) {
    // TODO Auto-generated method stub
    String filename = filename;
    String string = content;
    Context context = MyActivity.getAppContext();

    FileOutputStream outputStream;
    try {//Context.MODE_PRIVATE
        Log.v("insertR", content);
        System.out.println(filename);
        System.out.println(context); //prints null

        outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(string.getBytes());
        outputStream.flush();
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
 } }

public class MyActivity extends Activity {
public static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_simple_dynamo);
    context = getApplicationContext();

    TextView tv = (TextView) findViewById(R.id.textView1);
    tv.setMovementMethod(new ScrollingMovementMethod());
}
public static Context getAppContext() {
    try {
        return context;
    } catch (Exception e) {
        return MyActivity.getAppContext();
    }
}}

Solution

  • Change the insertR() method like this:

    synchronized public void insertR(Context context, String filename,String content) {
        // TODO Auto-generated method stub
        String filename = filename;
        String string = content;
    
        FileOutputStream outputStream;
    
        try {//Context.MODE_PRIVATE
            Log.v("insertR", content);
            System.out.println(filename);
            System.out.println(context); //prints null
    
            outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
            outputStream.write(string.getBytes());
            outputStream.flush();
            outputStream.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    

    If you want to call it from MainActivity do it like this:

    insertR(this, fileName, content);
    

    or

    insertR(getApplicationContext(), fileName, content);