I am using Titanium to build a cross-platform mobile application, which I mostly tested with the iOS simulator and where I already got all functionality working. Now I want to have the app also bugfree on Android. One of the issues I'm facing right now is that the remote images are not shown anymore (while they were on iOS). The url from the remote images can is retrieved from the server and should be correct, as I see the images on iOS. This is one of the image urls:
http://elgg.masaer.com/mod/profile/icondirect.php?joindate=1426024336&guid=47&size=large
This is the code I use to show the image:
var profilePic = Titanium.UI.createImageView({
image: post.User.avatar,
width: '60px',
height: '60px',
borderRadius: 5
});
Does anybody know what could be the issue. Maybe it is because the url doesn't really have an extension of the image file? Thanks in advance!
possible answer is this
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView mImgView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
mImgView1.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
After some searching I found out that android is not smart enough to work with image urls and you have to retrieve the imagedata yourself. This can be used to download the remote image.
function loadImage(imageView,url) {
var http = Titanium.Network.createHTTPClient();
http.onload = function() {
imageView.image=this.responseData;
};
http.open('GET',url);
http.send();
};
Related
I have been trying many of the codes that have been posted on stackoverflow itself. However, none have worked for me so far. I'm new to android and there's probably something I'm overlooking. Kindly help fix this code -
package com.alphageeks.pespitstop;
import java.io.InputStream;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class Vop extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vop);
Button bnot = (Button) findViewById(R.id.bnot);
Button bcant = (Button) findViewById(R.id.bcant);
Button bcal = (Button) findViewById(R.id.bcal);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final Toast disp = null;
bnot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = new URL("https://drive.google.com/file/d/0B-bEff6i-vWoUHpWS3h1VUR4ZkE/edit?usp=sharing");
//try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
disp.makeText(Vop.this, "error",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Two things:
1) The URL your want is actually:
https://lh3.googleusercontent.com/pgF2BkPGEdp5KuKD535q0DNL-SkXqiaPGmeQt-F0wA-GZ3GLIu2WaOGI72i0TzlxI-Uub4FoFtY
2) You'll need to download the image in a background Thread, like an AsyncTask, otherwise you'll throw a NetworkOnMainThreadException.
private class ImageWorker extends AsyncTask<String, Void, Bitmap> {
/**
* {#inheritDoc}
*/
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
final URL url = new URL(YOUR_URL);
input = new BufferedInputStream(url.openStream());
return BitmapFactory.decodeStream(input);
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (final IOException ignored) {
// Nothing to do
}
}
}
return null;
}
/**
* {#inheritDoc}
*/
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
// Set the image here
}
}
}
try this (this is in case if you don't get any exceptions, otherwise you probably do networking on UI thread and that results in error, then you may ignore my reply):
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
byte[] bytes = out.toByteArray();
Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
img.setImageBitmap(bmp);
Maybe you can take a look in this tutorial.
I hope it can solve your problem.
https://sites.google.com/site/androidhowto/diplayinganimage
Or this website that have more detailed tutorial on how to display image from URL.
Don't forget to include permission in the manifest.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
use picasso http://square.github.io/picasso/ is easy with less code example Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Try this..it may be help you..
URL url = new URL("YourUrl");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Try this:
try {
URL url = new URL("https://drive.google.com/file/d/0B-bEff6i-vWoUHpWS3h1VUR4ZkE/edit?usp=sharing");
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;
}
I have uploaded image on app engine. I am retrieving image blob key in android app from app engine using endpoints. I am doing some code on android app to display image.
The code is
URL imageURL = null;
try
{
//use our image serve page to get the image URL
imageURL = new URL("http://yourapp.appspot.com/serveBlob?id=" + o.getImageKey());
} catch (MalformedURLException e)
{
e.printStackTrace();
}
try {
//Decode and resize the image then set as the icon
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 1 / 2;
Bitmap bitmap = BitmapFactor.decodeStream((InputStream) imageURL.getContent());
Bitmap finImg = Bitmap.createScaledBitmap(bitmap, 50, 50, false);
icon.setImageBitmap(finImg);
} catch (IOException e)
{
e.printStackTrace();
}
but it gives me bitmap = null and throwing null pointer exception.
I am struck on this point from lat 4 days. Please help me.
Try this..
Bitmap bitmap = null;
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
Log.v("bitmap--", "" + bitmap);
icon.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
I got the answer.
First have to create Servlet on app engine side of my project.
Servlet is like this.
public class Serve extends HttpServlet
{
private BlobstoreService blobstoreService =BlobstoreServiceFactory.getBlobstoreService();
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
BlobKey blobKey = new BlobKey(req.getParameter("id"));
blobstoreService.serve(blobKey, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
doGet(req, resp);
}
}
Then have to register servlet in web.xml
<servlet>
<servlet-name>Serve</servlet-name>
<servlet-class>com.xyz.Serve</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Serve</servlet-name>
<url-pattern>/ServeBlob</url-pattern>
</servlet-mapping>
Then create url using servlet in android code.
the code at android side is like this.
URL imageURL = new URL("http://xyz.appspot.com/ServeBlob?id="+blobKey);
HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
xyz is your app engine project name on appspot.
blobKey should be the blob key of image store on AppEngine.
Now pass bitmap to image view like this.
ImageView img = (ImageView) findViewById(R.id....);
img.setImageBitmap(bitmap);
I have trouble with download image from server in my android app. If i try to download image from https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg
My Code -
bitmap = BitmapFactory.decodeStream((InputStream) new URL(url)
.getContent());
It return null means image not downloading on 4.0.3 but image downloading successfully on 2.2
I think there may be problem with os version.
Now i want anyone to help and guide me for the same.
Write below code into your activity.java file's onCreate method after setcontentview().
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Between 2.2 and 4.0.0 there were some changes regarding what you could do on the UI thread.
From your code snipit I can not tell what thread you are doing this on, but I would expect that this is the same problem.
Try loading your image using an AsyncTask, as you can not perform this http action on the UI thread.
Please confirm about Network on UI Thread Exception and make sure that you are using AsyncTask. Try the same code with AsyncTask, this will help you.
Try this code.
try
{
imageView.setImageDrawable(grabImageFromUrl(imageUrl));
}
catch (Exception e)
{
Log.i("CATCH", "ImageDrawable");
e.printStackTrace();
}
and method code is::
private Drawable grabImageFromUrl(String imageUrlInput) throws MalformedURLException, IOException, Exception
{
return Drawable.createFromStream((InputStream)new URL(imageUrlInput).getContent(), "src");
}
I have created this code for you, try it worked at my end...
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loading remote images
I am developing an application where I have a list in which each row has an image,
this image is loaded from a web URL.
below is my code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/list_row_img"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:id="#+id/list_row_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
and this is the activity code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img= (ImageView) findViewById(R.id.list_row_img);
Bitmap bm = null;
try {
URL aURL = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
img.setImageBitmap(bm);
bis.close();
is.close();
} catch (Exception e) {
Log.v("EXCEPTION", "Error getting bitmap", e);
}
}
when I run i get nothing on the device. only a gray screen and no exception happens.
note that i added this permission in the manifest file
<uses-permission android:name="android.permission.INTERNET" />
can anyone help me please ?
try this
you can exeecute it by
new DownloadImageTask((ImageView) im1).execute(url here);
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;
}
/* #Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgressDialog();
}*/
protected void onPostExecute(Bitmap result) {
//pDlg.dismiss();
bmImage.setImageBitmap(result);
}}
Use below code for download image from url and display image into imageview, this will solve your problem.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView mImgView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
mImgView1.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
The link for your image is invalid. Try to access it with your browser, you will find out. thats your problem.
I'd like to know how I can download an Image from a given URL and display it inside an ImageView. And is there any permissions required to mention in the manifest.xml file?
You need to put this permission to access the Internet
<uses-permission android:name="android.permission.INTERNET" />
you can try this code.
String imageurl = "YOUR URL";
InputStream in = null;
try
{
Log.i("URL", imageurl);
URL url = new URL(imageurl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.connect();
in = httpConn.getInputStream();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Bitmap bmpimg = BitmapFactory.decodeStream(in);
ImageView iv = "YOUR IMAGE VIEW";
iv.setImageBitmap(bmpimg);
Use background thread to get image and after getting image set it in imageview using hanndler.
new Thread(){
public void run() {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new URL("http://imageurl").openStream());
Message msg = new Message();
msg.obj = bitmap;
imageHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Handler code where we set downloaded image in imgaeview.
Handler imageHandler = new Handler(){
public void handleMessage(Message msg) {
if(msg.obj!=null && msg.obj instanceof Bitmap){
imageview.setBackgroundDrawable(new BitmapDrawable((Bitmap)msg.obj));
}
};
};
And ofcourse you need internet permission.
<uses-permission android:name="android.permission.INTERNET" />
You need to set usage permission of INTERNET in android manifest file and use java.net.URL and java.net.URLConnection classes to request the URL.
There is the BitmapFactory-class which can do that. It can create a Bitmap-object from an InputStream, which can then be displayed in an ImageView.
Something you should know is, that using a normal URLConnection to get an InputStream on a URL-object does not always work with the bitmap-factory. A work-around is presented here: Android: Bug with ThreadSafeClientConnManager downloading images
look this:
Option A:
public static Bitmap getBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
Option B:
public 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);
input.close();
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Jus run the method in a background thread.