Creating a bitmap from png file stored at sdcard (Android) - android

Im trying to create a Bitmap from a Png file stored on the SD card and then set that Bitmap in an imageView.
But its not working.
Here's the code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import com.pxr.tutorial.xmltest.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
public class Getbackground {
URL url;
public static long downloadFile(URL url2) {
try {
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();{
try {
File fileOnSD=Environment.getExternalStorageDirectory();
String storagePath = fileOnSD.getAbsolutePath();
OutputStream output = new FileOutputStream (storagePath + "/oranjelanbg.png");
try {
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.flush();
output.close();
//----------------------------------------------------------------------------------------------------------
Bitmap BckGrnd = BitmapFactory.decodeFile(storagePath + "/oranjelanbg.png");
ImageView BackGround=(ImageView)findViewById(R.id.imageView1);
BackGround.setImageBitmap(BckGrnd);
//----------------------------------------------------------=-----------------------------------------------
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
input.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
} catch (IOException e) {
throw new RuntimeException(e);
}
return 0;
}
//-----------------------------------------------------------------------------------------
private static ImageView findViewById(int imageview1) {
// TODO Auto-generated method stub
return null;
}
//-----------------------------------------------------------------------------------------
}
The File does load on the SD card succesfully but I cant seem to get the img in the view.

You can't..
ImageView BackGround=(ImageView)findViewById(R.id.imageView1);
BackGround.setImageBitmap(BckGrnd);
How can you get the reference of ImageView in non activity class Getbackground?
You can only update UI component in MainUI Thread and if its in non Activity class then using reference (Context) of that calling activity class only.
So put this code in your Activity class after Getbackground completes.

Related

PC to Android File Transfer through Sockets

How to transfer a file(unknown extension ie maybe a pdf/word/jpeg) from PC to Android Phone using Socket Programming. The Android Phone should be able to detect the type of file transfer and should be able to open it thereafter. Also the file should go into a specific folder named after app name in External storage.
I have tried following solution. However in this case, when I select the file to be transferred, the file transferred at Android side is of arbitrary size and not of the same size as of file selected, it is of some random size. Also the file transferred cannot be opened as it does not have a fixed extension.
Any help would be appreciated.
Android code(To receive file)
package minor.subham.com.pccontrol;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.net.*;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class getFile extends ActionBarActivity {
ImageView getFile;
public final static int SOCKET_PORT = Constants.SERVER_PORT; // you may change this
public final static String SERVER = Constants.SERVER_IP; // localhost
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_file);
getFile = (ImageView) findViewById(R.id.getFile);
getFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
final File file;
file = new File(Environment.getExternalStorageDirectory(), "PcControl");
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
// fos = new FileOutputStream(FILE_TO_RECEIVED);
try {
fos = new FileOutputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
fos.write(mybytearray);
fos.close();
System.out.println("File "
+ " downloaded (" + current + " bytes read)");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null) try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (sock != null) try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
thread.start();
}
});
}
}
And Her is the Java Code to send file. Suppose I want to send file temp.jpg
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class send {
public final static int SOCKET_PORT = 8991; // you may change this
public final static String FILE_TO_SEND = "temp.jpg"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
// while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
// }
}
finally {
if (servsock != null) servsock.close();
}
}
}

How to merge the two audio files into a single audio file in android?

I want to get two audio files as input, then merge them byte wise and save it as a single file.
In this code I have tried to do it in Java and it's working fine, but I don't know how to do it in android.
How to do it in android?
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class FileMixer {
public static void main(String[] args)
{
try
{
Path path1 = Paths.get("C:\\Srini\\Wav\\welcome.wav");
Path path2 = Paths.get("C:\\Srini\\Wav\\goodbye.wav");
String path3 ="C:\\Srini\\Wav\\srini12.wav";
File Newfilepath=new File(path3);
byte[] byte1 = Files.readAllBytes(path1);
byte[] byte2 = Files.readAllBytes(path2);
byte[] out = new byte[byte1.length];
for (int i=0; i<byte1.length; i++)
{
out[i] = (byte) ((byte1[i] + byte2[i]) >> 1);
}
InputStream byteArray = new ByteArrayInputStream(out);
AudioInputStream ais = AudioSystem.getAudioInputStream(byteArray);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE,Newfilepath);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
For combining two wav files use this code,
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class WavAppender {
public static void main(String[] args) {
String wavFile1 = "D:\\wavOne.wav";
String wavFile2 = "D:\\wavTwo.wav";
try {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("D:\\wavAppended.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
It is too late. But still, someone might need a proper solution. That is why I am suggesting using AudioMixer-android library. You can also perform a lot of audio processing things.

async task fails when i try to use params

guys. I have this code:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class MyPicGetTask extends AsyncTask<URL , Void, Bitmap>{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
#Override
protected Bitmap doInBackground(URL... urls) {
// TODO Auto-generated method stub
URL url = urls[0];
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return bmp;
}
}
it fails, but if i use AsyncTask and describe this class as inner in my activity - it's ok . I can not say the reason because i can not debug, i can see that debug tab opens when it fails but it is not informative for me. Any ideas? Sorry for my noob question
that's my Activity:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class PicActivity extends Activity implements OnClickListener{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
private URL url;
//"http://192.168.0.30/03.jpg";
/*
private class getPicTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... s) {
// TODO Auto-generated method stub
try {
url = new URL("http://192.168.0.93/image.php");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return null;
}
};
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///////////
try {
url = new URL("http://192.168.0.30/03.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyPicGetTask().execute(url);
image.setImageBitmap(bmp);
}
});
////////////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pic, menu);
////////////////
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("httpProgress", "Onclick()");
}
}
Add Log.d() code to doInBackground(...) to print out all exceptions that occur. That should tell you what's going wrong, e.g.
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (Exception e) {
Log.d("Async","EXCEPTION",e);
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
Log.d("Close","EXCEPTION",e);
}
}
When the MyPicGetTask is an inner class it has access to the bmp field. When you pulled it out of your activity it lost access to the bmp class field.
I would suggest reading Google's documentation and following their examples for AsyncTasks.
The bitmap you return from doInBackground should then be used to update your UI in onPostExecute.
protected void onPostExecute(Bitmap bitmap) {
image.setImageBitmap(bitmap);
}
Your asyncTask subclass needs access to image in order to update the UI, so having it as a inner class is one way to make sure it can do this.
Your AsyncTask if you're using it as a public class outside the activity in which you are calling it needs to recieve the context of that activity. There are a number of posts here, here and here that explain how to set this up.

Download Random Images from file server

This is my attempt. My files are hosted on my own servers mostly JPGs files. I'm trying to download them into my app. I failed to generate those images into my app. I follow the guide from this blog http://getablogger.blogspot.gr/2008/01/android-download-image-from-server-and.html
My xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HTTPImage load test"
/>
<Button android:id="#+id/get_imagebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get an image"
android:layout_gravity="center"
/>
<ImageView android:id="#+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
Coding
package com.example.downloadimages;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imView;
String imageUrl="http://myfilehosting.com/";
Random r;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r= new Random();
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
public void onClick(View view) {
// TODO Auto-generated method stub
//i tried to randomize the file download, in my server i put 4 files with name like
//jpg0.jpg, jpg1.jpg, jpg2.jpg so different file is downloaded in button press
int i =r.nextInt()%4;
downloadFile(imageUrl+i+".jpg");
}
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
};
}
there are several problems with your code:
you are trying to perform network operation (download file from remote server) from the UI thread. network operation must be executed from another thread. otherwise - exception been thrown.
one of the ways to launch the code from another thread is:
new Thread(new Runnable() {
#Override
public void run() {
downloadFile(imageUrl+i+".jpg");
}
}).start();
better approach would be using AsyncTask or IntentService (which also performing the code on separate thread)
second thing - you can't just create int array with the size of the input stream: if the image is too big, it can fail. try break the download to segments with fixed size (say 2058 bytes each segment) for example:
private HttpURLConnection conn;
private InputStream stream;
private FileOutputStream out;
private double fileSize;
private double downloaded;
public void downloadFile(String fileURL, String fileName) {
try {
conn = (HttpURLConnection) new URL(fileURL).openConnection();
fileSize = conn.getContentLength();
File file = new File(fileName);
out = new FileOutputStream(file);
conn.connect();
stream = conn.getInputStream();
while (status == DOWNLOADING) {
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1) {
out.close();
if (conn != null) {
conn.disconnect();
}
break;
}
out.write(buffer, 0, read);
downloaded += read;
}
} catch (Exception e) {
Log.e("downloadFile():", e.getMessage());
if (conn != null) {
conn.disconnect();
}
}
}

How to store images in Cache Memory

I am totally blank on this. I want to download the images from a Url and have to store it internally so that next time I need not connect to web and instead retrieve it from cache memory. But I am not sure how to do this. Can anyone help me with a code snippet.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
public class CacheStore {
private static CacheStore INSTANCE = null;
private HashMap<String, String> cacheMap;
private HashMap<String, Bitmap> bitmapMap;
private static final String cacheDir = "/Android/data/com.yourbusiness/cache/";
private static final String CACHE_FILENAME = ".cache";
#SuppressWarnings("unchecked")
private CacheStore() {
cacheMap = new HashMap<String, String>();
bitmapMap = new HashMap<String, Bitmap>();
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
if(!fullCacheDir.exists()) {
Log.i("CACHE", "Directory doesn't exist");
cleanCacheStart();
return;
}
try {
ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(fullCacheDir.toString(), CACHE_FILENAME))));
cacheMap = (HashMap<String,String>)is.readObject();
is.close();
} catch (StreamCorruptedException e) {
Log.i("CACHE", "Corrupted stream");
cleanCacheStart();
} catch (FileNotFoundException e) {
Log.i("CACHE", "File not found");
cleanCacheStart();
} catch (IOException e) {
Log.i("CACHE", "Input/Output error");
cleanCacheStart();
} catch (ClassNotFoundException e) {
Log.i("CACHE", "Class not found");
cleanCacheStart();
}
}
private void cleanCacheStart() {
cacheMap = new HashMap<String, String>();
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
fullCacheDir.mkdirs();
File noMedia = new File(fullCacheDir.toString(), ".nomedia");
try {
noMedia.createNewFile();
Log.i("CACHE", "Cache created");
} catch (IOException e) {
Log.i("CACHE", "Couldn't create .nomedia file");
e.printStackTrace();
}
}
private synchronized static void createInstance() {
if(INSTANCE == null) {
INSTANCE = new CacheStore();
}
}
public static CacheStore getInstance() {
if(INSTANCE == null) createInstance();
return INSTANCE;
}
public void saveCacheFile(String cacheUri, Bitmap image) {
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
String fileLocalName = new SimpleDateFormat("ddMMyyhhmmssSSS").format(new java.util.Date())+".PNG";
File fileUri = new File(fullCacheDir.toString(), fileLocalName);
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(fileUri);
image.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
cacheMap.put(cacheUri, fileLocalName);
Log.i("CACHE", "Saved file "+cacheUri+" (which is now "+fileUri.toString()+") correctly");
bitmapMap.put(cacheUri, image);
ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(new File(fullCacheDir.toString(), CACHE_FILENAME))));
os.writeObject(cacheMap);
os.close();
} catch (FileNotFoundException e) {
Log.i("CACHE", "Error: File "+cacheUri+" was not found!");
e.printStackTrace();
} catch (IOException e) {
Log.i("CACHE", "Error: File could not be stuffed!");
e.printStackTrace();
}
}
public Bitmap getCacheFile(String cacheUri) {
if(bitmapMap.containsKey(cacheUri)) return (Bitmap)bitmapMap.get(cacheUri);
if(!cacheMap.containsKey(cacheUri)) return null;
String fileLocalName = cacheMap.get(cacheUri).toString();
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
File fileUri = new File(fullCacheDir.toString(), fileLocalName);
if(!fileUri.exists()) return null;
Log.i("CACHE", "File "+cacheUri+" has been found in the Cache");
Bitmap bm = BitmapFactory.decodeFile(fileUri.toString());
bitmapMap.put(cacheUri, bm);
return bm;
}
}
Although the selected answer is correct, but it's a bit lengthy as its downloading image from the server first. Those who are just looking at how to save bitmap into cache for them we can use Android's native LruCache library. Here I have written a detailed article on the topic LruCache in Java & LruCache in Kotlin.
Java Class to save Bitmap in Cache:
import android.graphics.Bitmap;
import androidx.collection.LruCache;
public class MyCache {
private static MyCache instance;
private LruCache<Object, Object> lru;
private MyCache() {
lru = new LruCache<Object, Object>(1024);
}
public static MyCache getInstance() {
if (instance == null) {
instance = new MyCache();
}
return instance;
}
public LruCache<Object, Object> getLru() {
return lru;
}
public void saveBitmapToCahche(String key, Bitmap bitmap){
try {
MyCache.getInstance().getLru().put(key, bitmap);
}catch (Exception e){}
}
public Bitmap retrieveBitmapFromCache(String key){
try {
Bitmap bitmap = (Bitmap) MyCache.getInstance().getLru().get(key);
return bitmap;
}catch (Exception e){}
return null;
}
}

Categories

Resources