繁体   English   中英

从AsyncTask中的上下文读取R.string

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM