-1

I've a static AsyncTask and i need to get context, what can i do to get it?

I tried using WeakReference, example:

    private WeakReference<ScanActivity> activityReference;

    FetchPositionAsyncTask(ScanActivity context) {
        activityReference = new WeakReference<>(context);
    }

But Android Studio says:

Geocoder (android.content.Context, Locale) in Geocoder cannot be applied to (java.lang.ref.WeakReference, Locale)

This is my code:

private static class FetchPositionAsyncTask extends AsyncTask<String, Void, String> {

    private WeakReference<ScanActivity> activityReference;

    FetchPositionAsyncTask(ScanActivity context) {
        activityReference = new WeakReference<>(context);
    }

    @Override
    protected String doInBackground(String... params) {
        return null;
    }

    protected void onPostExecute(String result) {
        //TODO da mettere in doInBackground

        final AlertDialog.Builder builder;

        //GET ADDRESS FROM COORDINATES
        Geocoder geocoder = new Geocoder(activityReference, Locale.getDefault());
        try {
            DATA_LOCALITY = geocoder.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String DATA_ADDRESS = DATA_LOCALITY.get(0).getAddressLine(0);


        //TEST
        builder = new AlertDialog.Builder(activityReference.this);
        builder.setTitle("").setMessage("Latitude: " + latitude + " " + "Longitude: " + longitude + " " + "Accuracy: " + accuracy + " " + "Address: " + DATA_ADDRESS).setNeutralButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show().setCanceledOnTouchOutside(false);
    }
}

Here is how I set the code:

Geocoder geocoder = new Geocoder(activityReference, Locale.getDefault());

builder = new AlertDialog.Builder(activityReference);
shizhen
  • 12,251
  • 9
  • 52
  • 88
TheRed27
  • 25
  • 1
  • 12
  • 4
    Try using [`activityReference.get()`](https://docs.oracle.com/javase/7/docs/api/java/lang/ref/Reference.html#get()) rather than just `activivtyReference` – Mikhail Olshanski May 16 '19 at 09:03

2 Answers2

0

You need to use activityReference.get() to use the Context from your reference variable.

Ahmadul Hoq
  • 705
  • 5
  • 14
0

WeakReference<ScanActivity> and ScanActivity are different, you should use the real object using activityReference.get() and pass it to Geocoder. I.e.

Geocoder geocoder = new Geocoder(activityReference.get(), Locale.getDefault());
shizhen
  • 12,251
  • 9
  • 52
  • 88