0

I have parsed several items of weather data from an online xml file. One of the nodes is a URL of an image I want to display. I have managed to parse it and save it as a String variable and it displays in the app as a String. How do I get it to display the image instead of text? Thanks in advance!

codegirl
  • 21
  • 6

2 Answers2

1

First, you need to download the image and store it in a Bitmap object.

Then, display it with an ImageView.

This answer describes how you can do it in some detail.

Community
  • 1
  • 1
TZHX
  • 5,291
  • 15
  • 47
  • 56
  • 1
    I get a number of 'cannot be resolved' errors with this code despite adding all the recommended imports - am I missing something obvious or is the code out of date? Thanks – codegirl Oct 17 '12 at 13:03
  • Use async task to download the image. Download it in doInBackground() and in postExecute() update ui accordingly. Makes it more efficient. – Raghunandan Oct 17 '12 at 13:04
  • I'm new to Android development - are there any good tutorials you could recommend to do that? – codegirl Oct 17 '12 at 13:05
0
public class MainActivity extends Activity {
   ProgressDialog pd;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pd = new ProgressDialog(MainActivity.this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
    .execute("Your URL");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;
    DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
        }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
          pd = new ProgressDialog(MainActivity.this);
          pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    }



    protected Bitmap doInBackground(String... urls) {
    String urldisplay = urls[0];
    Bitmap mIcon11 = null;
    try {
    InputStream in = new java.net.URL(urldisplay).openStream();
    mIcon11 = BitmapFactory.decodeStream(in);
    } catch (Exception e) {
    Log.e("Error", e.getMessage());
    e.printStackTrace();
    }
    return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        pd.dismiss();
    bmImage.setImageBitmap(result);
    }
    }         
 }
Raghunandan
  • 132,755
  • 26
  • 225
  • 256