below is my code... but only a blank screen shows up, anyone know what's up?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
URL url;
try {
url = new URL("http://pennapps.com/biblioteka/images/C.jpg");
URLConnection conn=url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
ImageView image = new ImageView(this);
image.setImageBitmap(bm);
setContentView(image);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Without seeing the logs, it's tough to say, but a common pitfall is forgetting to request the INTERNET permission. In addition, it's highly recommended that you do not make web requests on the main (UI) thread. There is an excellent article on Multithreading for Performance that also covers the topic of image downloading.
You forgot the permission tag , else the code seems to be working
Related
I want to load an image from a URL but it doesn't work because the link doesn't have an extension
Can this be solved???
URL example :
http://t0.gstatic.com/images?q=tbn:ANd9GcRf1EqE2kyW12HSb9gZZ8eTIPqNgVkjFis4GkTTYONIpoQtkIde4zybZ4iAqGlIHQ_pnEX499Oa
How can this be done??
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.imageView1);
Bitmap bitImg = getBitmapFromURL("http://t0.gstatic.com/images?q=tbn:ANd9GcRf1EqE2kyW12HSb9gZZ8eTIPqNgVkjFis4GkTTYONIpoQtkIde4zybZ4iAqGlIHQ_pnEX499Oa");
img.setImageBitmap(bitImg);
}
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
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;
}
}
look at this post, i dont see his URL but i think Android libraries figure it out based on the data and headers:
BitmapFactory.decodeStream returning null when options are set
also, don't add an extension to a URL, it changes the URL!
http://www.google.com is not the same as http://www.google.com.html
load an image from a URL but it doesn't work because the link doesn't have an extension. Nonsense. Url.openconnection does not look at extensions. It does not work because you have a NetworkOnMainThreadException clearly visible in the LogCat. Never seen in the LogCat? Please go and look for it. Place your network code in an AsyncTask or thread to prevent this.
I'm trying to get a static image from a map and put on my Android layout. So, looking for it I've found a code talking about Google Static Maps. Awesome! I've tried some URLs on my PC and it's working perfectly!
But my problem was when I've put the URL in Android to test it. WHen I try to get the input stream (the image), it gives me FileNotFoundExceptioin, because when I tried to connect, it threw me a Bad Request (error 400)
Here is my code:
public class ImageLoadingTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... stringURL) {
Bitmap bmp = null;
try {
URL url = new URL(stringURL[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmp = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap result) {
mapView.setImageBitmap(result);
super.onPostExecute(result);
}
}
String for test
Do I need a key for this?? Why don't I need a key for doing it in a browser?
The URL you're sending to Google has a strange character in it. Before sending it, run a URLEncode.encode() on it or if you're always showing São Paulo you could say "Sao Paulo" and let Google figure it out, or "S%C3%A3o%20Paulo". Personally I think the first one is less error prone but it's up to you.
I had develop a mobile apps to load image from URL path.
Here is my code.
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e)
{
System.out.println("Exc="+e);
return null;
}
}
This method is work well in emulator which android API 10 but cannot work in android device. The device i use test is API 16 and 17.
Kindly look for help. Thanks.
Have you done this?:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and yes, you must be connected to the internet.
Try to move this code to a thread or AsyncTask. Http requests can't be done from main thread because of strict mode.Here check AsyncTask.
LotusUNSW is right, you have to add INTERNET permission but if it's working on emulator it seems that this permission is set .
EDIT :
Alternatively, you can try using this method :
(last code was a stupid copy paste without checking, available here)
Don't forget to do this in a separate thread (using AsyncTask for example)
But try this thing instead
private Bitmap getImageBitmap(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(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
and then
Bitmap b = getImageBitmap("http://sdsdsdsdsdsdsds");
if (b != null)
myImageView.setImageDrawable(d);
Source :here
Hi I am trying to use the HttpResponseCache introduced in Android 4.The docs do talk clearly about how to install the cache but I am at a complete loss on how to cache Images downloaded from the net.Earlier I was using the DiskLruCache to cache them. Would anyone point me towards some examples of working code where HttpResponseCache has been used..
Edit:- Can someone tell me what I am doing wrong here:-
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
final File httpCacheDir = new File(getCacheDir(), "http");
try {
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
Log.v(TAG,"cache set up");
} catch (Exception httpResponseCacheNotAvailable) {
Log.v(TAG, "android.net.http.HttpResponseCache not available, probably because we're running on a pre-ICS version of Android. Using com.integralblue.httpresponsecache.HttpHttpResponseCache.");
try{
com.integralblue.httpresponsecache.HttpResponseCache.install(httpCacheDir, httpCacheSize);
}catch(Exception e){
Log.v(TAG, "Failed to set up com.integralblue.httpresponsecache.HttpResponseCache");
}
}
TheMainListFrag gf=(TheMainListFrag) getSupportFragmentManager().findFragmentByTag("thelistfrags");
if(gf==null){
gf=TheMainListFrag.newInstance();
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.thelefty, gf,"thelistfrags");
ft.commit();
}
}
Then in the loader of TheMainListFrag, I do the below:-
public ArrayList<HashMap<String,String>> loadInBackground() {
String datafromServer = null;
ArrayList<HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
try {
String url = "someurl";
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
InputStream is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
datafromServer=sb.toString();
Log.v("fromthread",datafromServer);
// etc
//etc
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
Log.v("fromthread", e.getClass() + "--" + e.getMessage());
}
return al;
}
When i am connected to internet, it works fine, and in the directory http-the cache directory named above, i can see the files too. But when I am not connected to the internet, the data refuses to load.
When i load images from the net, i see the cache files named as .tmp , which i believe are termed as dirty as per DiskLruCache.
Please let me know if there is any other info that you want me to provide
From the section Force a Cache Response on the HttpResponseCache documentation:
Sometimes you'll want to show resources if they are available
immediately, but not otherwise. This can be used so your application
can show something while waiting for the latest data to be
downloaded. To restrict a request to locally-cached resources, add the
only-if-cached directive:
try {
connection.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
} catch (FileNotFoundException e) {
// the resource was not cached
}
This technique works even better in situations where a stale response
is better than no response. To permit stale cached responses, use the
max-stale directive with the maximum staleness in seconds:
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
When you enable HttpResponseCache, all HttpUrlConnection queries will be cached. You can't use it to cache arbitrary data, so I'd recommend keep using DiskLruCache for that.
In my case HttpResponseCache wasn't actually caching anything. What fixed it was simply:
connection.setUseCaches(true);
(This must be called on the HttpURLConnection before establishing connection.)
For finer grained control, max-stale can be used as Jesse Wilson pointed out.
I'm using the following code to grab images from the web. It uses Gridview and depending on position, picks a URL from an array. It works but the loading of images is often hit or miss. Almost every time I start the app, a different number of images load.
It also has issues when changing from portrait to landscape view, 5 out of 10 images may be displayed then I'll turn the device and usually lose all the images. Sometimes a few do show up though.
Any ideas on making this more robust?
try {
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {
Log.d("DEBUGTAG", "error...");
}
return null;
One thing I read is that there's a known bug with decoding Bitmaps from an InputStream, and the suggested fix from Google was to use a FlushedInputStream (example in below URL):
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
Also, I'd put the download code into an AsyncTask. Here's what I currently use for mine:
public static Bitmap loadImageFromUri(URI uri)
{
URL url;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
Log.v("URL Exception", "MalformedURLException");
return null;
}
try
{
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(new FlushedInputStream(input));
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
I just pass in a URI due to the way I've got the rest of my code set up, you could pass in a URL instead and skip the first part. This will keep the download from tying up your UI thread.