Using Android's System Cache - android

I would like to use Android's system cache when downloading images as per these previous instructions: android system cache. I was able to get the following code working but the log statements are telling me that the images are never being read from the cache.
try {
//url = new URL("http://some.url.com/retrieve_image.php?user=" + username);
URL url = new URL("http://some.url.com/prof_pics/b4fe7bdfa174ff372c9f26ce6f78f19c.png");
URLConnection connection = url.openConnection();
connection.setUseCaches(true);
Object response = connection.getContent();
if (response instanceof Bitmap) {
Log.i("CHAT", "this is a bitmap");
current_image.setImageBitmap((Bitmap) response);
}
else {
Log.i("CHAT", "this is not a bitmap");
Log.i("CHAT", response.toString());
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
current_image.setImageBitmap(BitmapFactory.decodeStream(bis));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have tried two different types of requests, one is to go through a PHP script that returns the image and another that is directly accessing the image file. I refresh the same image multiple times in a row and it never seems to get cached. For the direct image access, I get:
05-31 23:45:12.177 I/CHAT ( 2995): this is not a bitmap
05-31 23:45:12.177 I/CHAT ( 2995): org.apache.harmony.luni.internal.net.www.protocol.http.FixedLengthInputStream#40c1c660`
For the indirect image access, I consistently get:
05-31 23:45:14.550 I/CHAT ( 2995): this is not a bitmap
05-31 23:45:14.550 I/CHAT ( 2995): org.apache.harmony.luni.internal.net.www.protocol.http.ChunkedInputStream#40c02448

I found a better way to do it. If anyone else is having trouble after following the link android system cache, use this Google developer's blog post instead. The source code in that blog post is designed for a ListView but I am using it for all image retrievals. It downloads the image in an AsyncTask, puts a temporary image while downloading, and has an image cache. This last part is listed as a "Future Item" in the blog post, but if you download the source code, the cache is implemented. I had to modify the code slightly because the AndroidHttpClient isn't supported in 2.1. I switched it to a URL connection. So far, this looks to be a great image downloader class. Let's just hope it doesn't impact our already struggling memory management issues.

Related

save and laod image using universal image loader

Updated
So as suggested earlier, i used Universal image loader. But i am getting some error.
**This is the first time i am playing around with this kind of stuff.
Below are my codes :
Here is the code to save bitmap to internal storage using async:
Uri uri = Crop.getOutput(result);
try {
bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
finally {
new saveDpToDisk().execute(bmp);
}
class saveDpToDisk extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
try {
fos = openFileOutput("ProPic", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
return bmp;
}
}
and here is code to load image from storage using UIL:
#Override
protected Object doInBackground(Object[] params) {
FileInputStream fis;
try {
fis = openFileInput("ProPic");
String uri = String.valueOf(fis);
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheOnDisk(true).build();
ImageLoader loader = ImageLoader.getInstance();
loader.displayImage(uri, pro_pic, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return pro_pic;
}
}
And this is the error I am getting (app doesnt force close, error just appears in logcat
UIL doesn't support scheme(protocol) by default [java.io.FileInputStream#42987180]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
java.lang.UnsupportedOperationException: UIL doesn't support scheme(protocol) by default [java.io.FileInputStream#42987180]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromOtherSource(BaseImageDownloader.java:235)
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:97)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.downloadImage(LoadAndDisplayImageTask.java:290)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryCacheImageOnDisk(LoadAndDisplayImageTask.java:273)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:229)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:135)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
________x_____________________x___________________________x_______________________
Original Question
My app has to load only one image (which user can select from gallery to set as his dp for that app).
So, What I did is I saved the selected pic to storage using FileOutputStream and then load the pic using FileInputStream in activity's onResume method.
But, what happens is that when the selected pic is too large, the app starts up too slowly (takes time to inflate view) and logcat shows memory heap of 30-60 MB.
So, i thought of storing the image in cache and load but dont exactly find a way to do so.
Shall i use picasso? If yes, how to use it for saving and laoding from cache.
Or are there any other ways to achieve what i need?
If you read this post on G+ by Koush you will get clear solutions for your confusions, I have put the summery of that, in that Android-Universal-Image-Loader is the winner for your requirement!
Picasso has the nicest image API if you are using network!
UrlImageViewHelper + AndroidAsync is the fastest. Playing with these
other two great libraries have really highlighted that the image API
is quite dated, however.
Volley is slick; I really enjoy their pluggable backend transports,
and may end up dropping AndroidAsync in there. The request priority
and cancellation management is great(if you are using network)
Android-Universal-Image-Loader is the most popular one out there
currently. Highly customizable.
This project aims to provide a reusable instrument for asynchronous
image loading, caching and displaying. It is originally based on Fedor
Vlasov's project and has been vastly refactored and improved since
then.
Considering all this Android-Universal-Image-Loader suites your requirement (Loading the images are on disk locally)!

Upload photo to picasa from android?

I'm new to android programming. I'm looking for a simple way to send pictures to Picasa, I looked at a lot of projects on it. I'm just looking to send a JPEG or PNG button I click, sends and displays a message that it is OK.
I know that is required a Google API and client authentication, but a lot of people show the same Intention sent.
Please help (sorry for the english: P)
I found this:
http://code.google.com/p/google-api-java-client/source/browse?repo=samples#hg/picasa-android-sample
Someone knows how to use it? But from the basics, I'm lost.
The only existing code in online for uploading photos to Picasa is this one..
Picasa Photo Uploader
Try with this one whether it can meet your requirements.If it does,then engage it with a button click event and display message on notification.finished() event to ensure that the file has been uploaded.
Quite an old post, but just for future references, I was successful in directly using http post to upload my image to Picasa. Their own Java API keeps returning errors.
I've written about this method in detail here:
File image = new File("/path/to/image.jpg");
byte[] imageContent = null;
try {
imageContent = Files.toByteArray(image);
} catch (Exception e) {
// do something
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://picasaweb.google.com/data/feed/api/user/default/albumid/default");
httpPost.addHeader("Authorization", "Bearer " + mAccessToken);
httpPost.addHeader("Content-Type", "image/jpeg");
httpPost.setEntity(new ByteArrayEntity(imageContent));
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// log the response
logd(EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e){
// do something
}
This method uses Apache's HttpClient. If your Android version does not support it, you can still include this line in your Gradle file to compile it:
compile 'cz.msebera.android:httpclient:4.4.1.1'

android size of remote file in java

I guess this quesiton has been answered already, buy it doesn't seem to work, and it is very furstrating...
I am just trying to get the size of a remote file in Android.
So far, I have tried the following two approaches, without success:
1)
try
{
file = new File("http://50.19.156.118/feed2/storage/download/a_17/Madagascar.3gp");
a=(int) myFileBeingUploaded.length();
}
catch (Exception j)
{
}
2)
try
{
url = new URL("http://50.19.156.118/feed2/storage/download/a_17/Madagascar.3gp);
urlConnection = (HttpURLConnection) url.openConnection();
a=urlConnection.getContentLength();
}
catch (Exception e)
{
}
getContentLength() returns always 77 !!, while File.length() returns 0
Any ideas?
Many thanks
HTTP is not a filesystem -- it is a protocol for communicating hyperlinked resources. With standard HTTP, the only way to determine the size of a resource is to download that resource. The way to solve your problem, assuming that you want the size before you want the resource, is to implement another resource which tells you the size. True, the Content-Size field of a response tells you the size of the data contained in the response, but only after you request the resource.
e.g. given your web server with image portrait.jpg, you could set up a php script meta.php to which you pass the name of the resource of interest... meta.php?f=portrait.jpg. Then meta.php would ask its filesystem for the size of f and return that number via HTTP.

Uploading to picasa from android app

I'm developing an app for which I need to be able to upload pics to picasa open album.
Ive gone through many threads,forums... tried a couple of methods using http post but none seems to work.
Has anyone did it before? If so can you share a sample code.I just need to do the basic upload and dload of pics from picasa.
The following question looks to cover some of this.
Picasa access in android: PicasaUploadActivity
This thread also has information. http://www.mail-archive.com/android-developers#googlegroups.com/msg43707.html
It looks straight forward to fire off the intent to use the standard picasa uploader. I will try putting this in my app later today as I want this function.
Doing it yourself looks to be possible but clearly more complex documentation looks to be http://code.google.com/apis/picasaweb/docs/2.0/developers_guide_protocol.html
OK I have got it working with the following code in my app. This brings up the picasa uploader.
Intent temp = new Intent(Intent.ACTION_SEND);
temp.setType("image/png");
temp.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
temp.putExtra(Intent.EXTRA_STREAM, fileUri);
temp.setComponent(new ComponentName(
"com.google.android.apps.uploader",
"com.google.android.apps.uploader.clients.picasa.PicasaSettingsActivity"));
try {
startActivity(temp);
} catch (android.content.ActivityNotFoundException ex) {
Log.v(TAG, "Picasa failed");
}
In practice I am going to take the set component bit out which lets the use choose where and how to send which is what I want.
The above answer was for Picasa API v2, which is now deprecated. I was not able to successfully use the Java API for Picasa API v3, but I figured out a way to upload images to Picasa using http post. I've written about this method here:
File image = new File("/path/to/image.jpg");
byte[] imageContent = null;
try {
imageContent = Files.toByteArray(image);
} catch (Exception e) {
// do something
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://picasaweb.google.com/data/feed/api/user/default/albumid/default");
httpPost.addHeader("Authorization", "Bearer " + mAccessToken);
httpPost.addHeader("Content-Type", "image/jpeg");
httpPost.setEntity(new ByteArrayEntity(imageContent));
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// log the response
logd(EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e){
// do something
}
This method uses Apache's HttpClient. If your Android version does not support it, you can still include this line in your Gradle file to compile it:
compile 'cz.msebera.android:httpclient:4.4.1.1'

How to use Android's CacheManager?

I'm currently developing an Android application that fetches images using http requests. It would be quite swell if I could cache those images in order to improve to performance and bandwidth use.
I came across the CacheManager class in the Android reference, but I don't really know how to use it, or what it really does.
I already scoped through this example, but I need some help understanding it:
/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java
Also, the reference states:
"Network requests are provided to this component and if they can not be resolved by the cache, the HTTP headers are attached, as appropriate, to the request for revalidation of content."
I'm not sure what this means or how it would work for me, since CacheManager's getCacheFile accepts only a String URL and a Map containing the headers. Not sure what the attachment mentioned means.
An explanation or a simple code example would really do my day. Thanks!
Update
Here's what I have right now. I am clearly doing it wrong, just don't know where.
public static Bitmap getRemoteImage(String imageUrl) {
URL aURL = null;
URLConnection conn = null;
Bitmap bmp = null;
CacheResult cache_result = CacheManager.getCacheFile(imageUrl, new HashMap());
if (cache_result == null) {
try {
aURL = new URL(imageUrl);
conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
cache_result = new CacheManager.CacheResult();
copyStream(is, cache_result.getOutputStream());
CacheManager.saveCacheFile(imageUrl, cache_result);
} catch (Exception e) {
return null;
}
}
bmp = BitmapFactory.decodeStream(cache_result.getInputStream());
return bmp;
}
I don't think the CacheManger can be used outside of a WebView as noted in this bug report
http://code.google.com/p/android/issues/detail?id=7222
I came across this issue awhile ago as well. The cache manager is only for the webview and not really useful outside of that. For my application I needed to cache xml responses and images so I ended up writing my own cache manager to accomplish that. Nothing too terrible but certainly not as easy as using a would-be built-in one.
If you have any questions about the specifics, add a comment to my post, I check back frequently.

Categories

Resources