getContext()返回Null

时间:2018-08-01 18:50:58

标签: android file-io android-contentprovider

我在Android中使用getContext()方法获取Context,然后创建文件。但是,当我从崩溃中调用应用程序,然后访问getContext()时,我始终会得到一个空指针异常。

下面是崩溃后调用的我的代码。该代码在崩溃之前可以正常工作,但是在崩溃之后失败。

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();
    }
}}

2 个答案:

答案 0 :(得分:0)

我相信,由于您处于活动中,因此可以使用静态函数getApplicationContext()来检索上下文。

答案 1 :(得分:0)

像这样更改insertR()方法:

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();
    } 
}

如果要从MainActivity调用它,请执行以下操作:

insertR(this, fileName, content);

insertR(getApplicationContext(), fileName, content);