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!
Asked
Active
Viewed 2,087 times
2 Answers
1
First, you need to download the image and store it in a Bitmap object.
Then, display it with an ImageView.
-
1I 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
-
This should work for download image. In your postExecute you can display the image. – Raghunandan Oct 17 '12 at 13:10
-
url1 = new URL("ur url); url1.openConnection().setConnectTimeout(1000); your bitmap =BitmapFactory.decodeStream(url1.openConnection().getInputStream()); – Raghunandan Oct 17 '12 at 13:17
-