简体   繁体   中英

(Android App) Trying to set AlertDialog .setIcon() as an image downloaded from URL

Currently making an app with a locations screen, when a map marker is pressed an AlertDialog pops up with some information. I want to set the icon for the AlertDialog to an image associated with that location that is from a URL. There are too many locations for images to be stored local.

 public Drawable pGraphic = null;

public class LoadImageFromWeb extends AsyncTask<String, Void, Drawable> {
    protected Drawable doInBackground(String... urls) {


        try {
            InputStream is = (InputStream) new URL(urls[0]).getContent();

            Drawable d = Drawable.createFromStream(is, "src name");
            BT_debugger.showIt(d.toString());
            return d;
        } catch (Exception e) {
            BT_debugger.showIt(e.toString());
            return null;
        }

    }
    protected void onPostExecute(Drawable result) {
        BT_debugger.showIt("Image Loaded");
        pGraphic = result;


    }
}
//handleMarkerClick..
public void handleMarkerClick(final int markerIndex) {

    BT_debugger.showIt(fragmentName + ":handleMarkerClick");

    //vars used in callout bubble...
    BT_item tappedItem = null;
    String latitude = "";
    String longitude = "";
    String title = "";
    String subTitle = "";
    String loadScreenWithItemId = "";
    String loadScreenWithNickname = "";
    String calloutTapChoice = "";
    Drawable pinGraphic = null;

    //if marker index == -1 then the user tapped the device's location icon...
    if(markerIndex == -1){
        BT_debugger.showIt(fragmentName + ":handleMarkerClick. Device location tapped");

        //use the graphic for the device location...
        pinGraphic = getResources().getDrawable(R.drawable.bt_screen_map_marker_device);

        //latitude / longitude is current location or last saved location...
        if(mapView.isMyLocationEnabled()){

            Location deviceLoc = mapView.getMyLocation();
            latitude = String.valueOf(deviceLoc.getLatitude());
            longitude = String.valueOf(deviceLoc.getLongitude());

            //title, subTitle...
            title = pokegoaus_appDelegate.rootApp.getRootDevice().getDeviceModel();
            subTitle = getString(R.string.mapUserLocationDescription) + "\nLatitude: " + latitude + "\nLongitude: " + longitude; 

        }else{

            //latitude / longitude is last current saved...
            latitude = goaus_appDelegate.rootApp.getRootDevice().getDeviceLatitude();
            longitude = goaus_appDelegate.rootApp.getRootDevice().getDeviceLongitude();

            //title, subTitle...
            title = goaus_appDelegate.rootApp.getRootDevice().getDeviceModel();
            subTitle = getString(R.string.mapUserLocationDescription) + "\nLatitude: " + latitude + "\nLongitude: " + longitude; 

        }//isMyLocationEnabled...

    }else{

        //get the BT_item at this index...
        tappedItem = childItems.get(markerIndex);
        latitude = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "latitude", "");
        longitude = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "longitude", "");
        title = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "title", "");
        subTitle = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "subTitle", "");
        loadScreenWithItemId = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "loadScreenWithItemId", "");
        loadScreenWithNickname = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "loadScreenWithNickname", "");
        calloutTapChoice = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "calloutTapChoice", "");


        String pinColor = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "pinColor", "red");
        String locationImage = BT_strings.getJsonPropertyValue(tappedItem.getJsonObject(), "locationImage", "");
        new LoadImageFromWeb().execute("http://pheds.com.au/example1.png");


        BT_debugger.showIt(fragmentName + ":handleMarkerClick. Tapped: \"" + title + "\"");

    }//not the device's location...

    //are we showing the details button on this locations pup-up bubble?
    boolean showDetailsButton = false;
    if(loadScreenWithItemId.length() > 1 || loadScreenWithNickname.length() > 1){
        showDetailsButton = true;
    }

    //if we are showing directions we are not showing details bubble...
    if(loadScreenWithItemId.equalsIgnoreCase("showDirections")){
        showDetailsButton = false;
    }

    //if we did not find load screen from id or nickname, look for a load sceen object...
    if(!showDetailsButton){
        try{
            if(tappedItem != null){
                JSONObject obj = tappedItem.getJsonObject();
                if(obj.has("loadScreenObject")){
                    showDetailsButton = true;
                }
            }
        }catch(Exception e){
            showDetailsButton = false;
        }
    }
    pinGraphic = pGraphic;
    final AlertDialog myAlert = new AlertDialog.Builder(this.getActivity()).create();
    myAlert.setTitle(title);
    myAlert.setMessage(subTitle);
    myAlert.setIcon(pinGraphic);
    myAlert.setCancelable(false);
    myAlert.setButton2(getString(R.string.ok), new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            myAlert.dismiss();
        } }); 

    //do we show details button?
    if(showDetailsButton){
        myAlert.setButton(getString(R.string.details), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                myAlert.dismiss();
                showDetailsScreen(markerIndex);
         } }); 
    }

    //do we show the driving directions button?
    if(loadScreenWithItemId.equalsIgnoreCase("showDirections") || calloutTapChoice.equalsIgnoreCase("showDirections")){
        myAlert.setButton(getString(R.string.mapDrivingDirections), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                myAlert.dismiss();
                showDirections(markerIndex);
        } }); 
    }

    //show...
    myAlert.show();

}

It seems as though the image is being downloaded. But I am unsure how to handle the downloaded image and use it in my AlertDialog. With LoadImageFromWeb being an AsyncTask class Im not sure how to use the result as a Drawable.

Thanks in advance

Kristan Halls

Immaculate Apps

It seems like you are not waiting for the Drawable to be downloaded. You immediately set it as the AlertDialog's icon.

You would be better off using Glide for downloading and displaying images from the web. It's much more efficient and easier to use than a standart AsyncTask. Here's how you'd do it with Glide -

Glide.with(this)
    .load("http://pheds.com.au/example1.png")
    .into(new SimpleTarget<GlideDrawable>(drawableWidth, drawableHeight) {
        @Override
        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
            myAlert.setIcon(resource);
        }
    });

Edit: Import the following -

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

First use setFeatureDrawable(int featureId, Drawable drawable) like this:

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setFeatureDrawable(Window.FEATURE_LEFT_ICON, drawableFromUrl(YOUR_URL)); 
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Dialog Title");
dialog.show();

To get the image use this ( https://stackoverflow.com/a/9490060/4198633 ):

public static Drawable drawableFromUrl(String url) throws IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return new BitmapDrawable(x);
}

And you'll need this, of course:

<uses-permission android:name="android.permission.INTERNET" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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