gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:34:29 25 4
gpt4 key购买 nike

我是 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 的类(class):

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

this is because you havent initialized the context ..

关于java - 从 AsyncTask 的上下文中读取 R.string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com