[英]read R.string from context in AsyncTask
我是Java的新手,但不是編程的新手,但是有人可以幫助解釋為什么從AsyncTask讀取R.string時遇到以下崩潰嗎?
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
我有一個與AsyncTask的類:
public class getBitmapFromURL extends AsyncTask<String, Void, Bitmap>{
ImageView bmImage;
private Context mContext;
public getBitmapFromURL( Context context, ImageView bmImage) {
this.bmImage = bmImage;
mContext = context;
}
在doInBackground方法中:
protected Bitmap doInBackground(String... urls) {
try {
savebitmap( mIcon11, target_file[1]);
} catch (IOException e) {
e.printStackTrace();
}
}
以及文件保存方法本身:
private File savebitmap(Bitmap bmp, String file_name) throws IOException {
//**** --- >>> This line causes the crash:
String app_name = mContext.getApplicationContext().getString(R.string.app_name);
Log.e( "APP_NAME INFO:", app_name);
File app_dest_folder = new File(Environment.getExternalStorageDirectory () + "/" + app_name );
if(!app_dest_folder.exists()){
app_dest_folder.mkdir();
...
調用AsyncTask是從GetContent類完成的:
public class GetContent extends AppCompatActivity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_content);
loadimages();
}
public void loadimages() {
new getBitmapFromURL(context, (ImageView)findViewById(R.id.wc_latest_iv)).execute(url);
}
...
使用它來執行asynctask類
new getBitmapFromURL(GetContent.this, (ImageView)findViewById(R.id.wc_latest_iv)).execute(url);
這是因為您尚未初始化
context
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.