0

I am new to Java, but not to programming, however can anyone help to explain why I have following crashes when dealing with reading of R.string from AsyncTask?

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

I have a class with 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;
    }

within doInBackground method:

protected Bitmap doInBackground(String... urls) {

try {
            savebitmap( mIcon11, target_file[1]);
        } catch (IOException e) {
            e.printStackTrace();
        }
}

and the file saving method itself:

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

calling AsyncTask is done from GetContent class:

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

...
B.Ondrej
  • 381
  • 4
  • 14

1 Answers1

1

Use this to execute asynctask class

   new getBitmapFromURL(GetContent.this, (ImageView)findViewById(R.id.wc_latest_iv)).execute(url);

this is because you havent initialized the context ..

Santanu Sur
  • 10,997
  • 7
  • 33
  • 52