首页 > 解决方案 > getContext() 返回 Null

问题描述

我在 Android 中使用 getContext() 方法来获取上下文,然后创建文件。但是,当应用程序从崩溃中被调用时,我总是得到一个空指针异常,然后访问 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();
    }
}}

标签: androidfile-ioandroid-contentprovider

解决方案


我相信既然你在一个活动中,你可以使用静态函数getApplicationContext()来检索上下文。


推荐阅读