android - 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();
}
}}
解决方案
我相信既然你在一个活动中,你可以使用静态函数getApplicationContext()
来检索上下文。
推荐阅读
- asp.net-mvc - 当我移动到日期时间时,滚动变得可见
- filter - 使用 Pyspark 的 Hbase 过滤器
- sql - TRIM 不是公认的内置函数名称
- c++ - 打印 ppm 文件的数组时出现问题
- pimcore - Pimcore ImportDefinitions根据csv列名设置对象id
- c# - 在集成测试中获取 IHostingEnvironment
- javascript - 如何在three.js中创建纹理然后通过shader渲染?
- powershell - 包含特定租户域名的电子邮件地址
- c# - (构建失败)添加迁移初始
- javascript - Webpack编译的javascript在开发模式下无法在android上运行