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!
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.
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);
}
}
}
Related
how to get tweet post with image and display it on list view?
i'm only getting text in retrieving tweet post on twitter.
this is what i wanted to do http://tinypic.com/r/2ztee84/8
and this is what I've done on my application http://tinypic.com/r/zkmknm/8
thanks in advance.
Well, it would help if you provided us with more code. But... Try to "parse" the image link from the tweet, and download it.
You could try this lib, which will download images asynchronously. Or you could try a native approach. Something like:
public class LoginActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
this.findViewById(R.id.userinfo_submit).setOnClickListener(this);
// Verify Code
LinearLayout view = (LinearLayout) findViewById(R.id.txt_verify_code);
view.addView(new VerifyCodeView(this));
// show The Image
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(“http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png”);
}
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
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) {
bmImage.setImageBitmap(result);
}
}
}
This code was taken from here.
And there's this related question, which might be an interesting read for you.
I have an image view in my Android app, where I have to set a simple image from url. I tried the below code, but it doesn't set the image from url.
try {
URL url = new URL("https://drive.google.com/...");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap teamBmpImage = BitmapFactory.decodeStream(stream);
teamImgView.setImageBitmap(teamBmpImage);
}
catch (Exception e) {
}
Could someone guide me to achieve this please?
UPDATED CODE: Which gives Nullpointer exception
public class AboutActivity extends ActionBarActivity {
ImageView teamImgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
teamImgView = (ImageView) this.findViewById(R.id.teamImageView);
new DownloadImageTask(teamImgView).execute("http://docs.oracle.com/javase/tutorial/2d/images/examples/strawberry.jpg");
}
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//pd.show();
}
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;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//pd.dismiss();
bmImage.setImageBitmap(result);
}
}
}
I guess you are executing your code on the MainThread, which leads to a NetworkOnMainThreadException in android. Try to execute your code asynchronous like in the example below
new AsyncTask<String, Integer, Bitmap>() {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bm) {
ImageView teamImgView = (ImageView) findViewById(R.id.teamImageView);
teamImgView.setImageBitmap(bm);
}
}.execute("https://drive.google.com/uc?....");
You can use Picasso library and here is a detailed tutorial on how to do this.
This is very simple example usage
Picasso.with(activityContext)
.load("https://drive.google.com/uc?....")
.placeholder(R.drawable.image_name)
.into(imageView);
As bojan says you can use Picasso library wich handles many common pitfalls of image loading on Android.
Picasso.with(context).load("http://myurl/myImage.png").into(imageView);
Picasso
Anyway, check out this threat too :)
How to load an ImageView by URL in Android?
Try following this link:
http://www.tutorialsbuzz.com/2014/11/android-volley-url-imageview.html
This will help you to load your image using Volley library which will do all the networking stuff on networking thread and set your image on main UI thread. It has also the LRUCache part which you can skip if you want.
I want to open a url of an image from another url of an image using intent.I am new to android so this code of mine not working.
url_1 = new URL("http://garooh.905pm.com"+com.org.constant.Helper.Gadd_list.get(0).thisEvent.getImage_four_thumb());
url_2 = new URL("http://garooh.905pm.com"+ com.org.constant.Helper.Gadd_list.get(0).thisEvent.getImage_four_thumb());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(url_1, url_2);
startActivity(intent);
Am i right in thinking you have an imagebutton and when you click it you want to go to 1 of those URLs?
Try adding this to your imageButton.
imageButton.setOnClickListener(new locatorButtonClickListener());
private class imageButtonListener implements OnClickListener
{
#Override
public void onClick(View button) {
new DisplayImageFromUrl((ImageButton) findViewById(R.id.imageButtonEnd), this).execute(//Enter your link here);
}
UPDATE
Try using this Async task
//Display image to bitmap using URL
public class DisplayImageFromUrl extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
Context context1;
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context1);
pd.setMessage("Loading Images...");
pd.show();
}
public DisplayImageFromUrl(ImageView bmImage, Context context) {
this.bmImage = bmImage;
this.context1 = context;
}
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) {
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
and you call it like this in your activity.
new DisplayImageFromUrl((ImageButton) findViewById(R.id.imageButtonEnd), this).execute(//Enter your link here);
I'm trying to display an image from a url in a "InfoWindowAdapter"
,I have the following code, but does not show me the image
....
mMap = getMap();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
...
#Override
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(
R.layout.info_window_layout, null);
String image_url = "http://api.androidhive.info/images/sample.jpg";
new DownloadImageTask(imgEquipo).execute(image_url);
return v;
}
});
call to AsyncTask to get image
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
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) {
bmImage.setImageBitmap(result);
} }
}
tranks for your help.
It won't work because the view is returned before you get the image, and they are not synchronized.
Take a look at this approach:
I my using google mapV2 and i m downloading image from google place api and want to display in the popup
The trick is to update the InfoWindow after you get the image.
I have an Async running to get data from a page I've created. It get's the text just fine, but when I try and get the image from the image src via another class the app force closes. Here is the code that it force closes on:
public class FullReportActivity extends NavigationActivity {
private TextView textView;
private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
private ImageView ivDangerRose;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// tell which region this covers
getSupportActionBar().setSubtitle("...from Sierra Avalanche Center");
setContentView(R.layout.activity_fullreport);
textView = (TextView) findViewById(R.id.todaysReport);
ivDangerRose = (ImageView) findViewById(R.id.dangerRose);
fetcher task = new fetcher();
task.execute();
}
// GET THE IMAGE and RETURN IT
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class fetcher extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
FullReportActivity.this);
private Document doc = null;
private Document parse = null;
private String results = null;
private String reportDate = null;
private Bitmap bimage = null;
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
parse = Jsoup.parse(doc.html());
results = doc.select("#fullReport").outerHtml();
Element dangerRoseImg = doc.getElementById("reportRose")
.select("img").first();
String dangerRoseSrc = dangerRoseImg.absUrl("src");
Log.i("Report Rose IMG", dangerRoseSrc);
bimage = getBitmapFromURL(dangerRoseSrc);
ivDangerRose.setImageBitmap(bimage);
return results;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportDate = parse.select("#reportDate").outerHtml();
textView.setText(Html.fromHtml(reportDate + results));
textView.setPadding(30, 20, 20, 10);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Full Report from the Sierra Avalanche Center...");
dialog.show();
}
}
}
I have run this Async alone to get the image like so without a force close and I don't understand what i am doing different besides calling the method:
public class MainActivity extends Activity {
public String durl = "http://www.sierraavalanchecenter.org/dangerrose.png?a=2955";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadImageTask((ImageView) findViewById(R.id.dangerrose))
.execute(durl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap drose = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
drose = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return drose;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
This class gets the image src and creates a bitmap and puts it into an ImageView, what is different here than on my first class???
Frustrated.
You can not modify UI from background thread.
move ivDangerRose.setImageBitmap(bimage); in onPostExecute
In the method doInBackground
remove --> ivDangerRose.setImageBitmap(bimage);
as you can't modify UI in background process.
If you still want you can try runOnUiThread Method
In doInBackground() we should not access the content of activity.