Android Gallery view with images saved in sqlite as blob - java

i need to show images from sqlite database into gridview or gallery view.
this is the code for displaying on a single view:
mMain = (ImageView) findViewById(R.id.ivMain);
byte[] blob = imgs.getBytes(); //there is a method that will return the bytes from the database
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mMain.setImageBitmap(bitmap);
i have the android tutorial for grid view but it gets the image from file
// references to our images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3
... }
is there a way to populate the gridview from the sqlite database?
UPDATE:
Im using the ImageAdapter provide in android tutorial:
http://developer.android.com/resources/tutorials/views/hello-gridview.html
my code becomes this:
ArrayList<byte[]> image_arr = new ArrayList<byte[]>();
//loop through all images on sqlite
for(int l = 0 ;l< db.getAllImages().size(); l++){
Image imgs = db.getAllImages().get(l);
byte[] blob = imgs.getBytes();
image_arr.add(blob);
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// mMain.setImageBitmap(bitmap);
}
//TODO; find way to make the bitmap get to the ImageView
Gallery gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
This code is on main activity so i need to find way to pass the resources in ImageView which is in other file.

private void getDataAndPopulate() {
image = new ArrayList<byte[]>();
caption = new ArrayList<String>();
cursor=db.rawQuery("select * from NAME",null);
while (cursor.moveToNext()) {
byte[] temp_image = cursor.getBlob(2);
String temp_caption = cursor.getString(1);
String temp_id= cursor.getString(0);
image.add(temp_image);
caption.add(temp_caption);
id.add(temp_id);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);
ItemsAdapter itemsAdapter = new ItemsAdapter(Item_show_grid.this, R.layout.item_grid,captionArray);
gv.setAdapter(itemsAdapter);
}

Related

OnBindViewHolder not called unless I save a file first

Update #2
Thanks to AgentP for hinting my problem . I have fixed this issue by making this change inside showImages() :
(Also created a global reference field String path; in the same activity) :
private void showImages(){
// Added following two lines :
ContextWrapper cw = new ContextWrapper(this); // + added
path = cw.getDir("files", Context.MODE_PRIVATE).toString(); // + added
// String path = DrawingActivity.path; // - removed
allFilesPaths = new ArrayList<>();
allFilesPaths = listAllFiles(path);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.galleryRecycleViewId);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 3);
recyclerView.setLayoutManager(layoutManager);
ArrayList<Cell> cells = prepareData();
ImageAdapter adapter = new ImageAdapter(getApplicationContext(), cells);
recyclerView.setAdapter(adapter);
}
Update
Apparently I have a static string that is only set inside save image method . It's purpose is to give image folder path to the show images method. I'm trying to provide path to my showImages() method via other means now .
Old
I have a gallery activity that displays images from a folder with recycler view .
When I start my app the gallery is empty despite having images in the folder .
When I go to my drawing activity , save an image and return to gallery activity it shows all images without problems .
I placed a log inside onbindviewholder method and it only executes after I save an image.
What functionality is missing for image adapter to see exiting files and what does image saving do to make it find them when executed ?
(Also I remember when I wrote the save image method that it wanted me to do #SuppressLint("WrongThread") , but now it works without it)
Debug info when opening gallery without saving a file in drawing activity:
ClassLoader referenced unknown path: /data/app/com.example.myapp-2/lib/x86_64
Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
Methods involved in displaying images inside Gallery Activity :
List <Cell> allFilesPaths;
// on create calls show images after checking if read storage permission is good
private void showImages(){
// this is the current problem line ,
// I need a way to give path of my image folder to this method
// Check SaveImage() method below to see how it is initially set
// path is a global static field inside drawing activity
String path = DrawingActivity.path;
allFilesPaths = new ArrayList<>();
allFilesPaths = listAllFiles(path);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.galleryRecycleViewId);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 3);
recyclerView.setLayoutManager(layoutManager);
ArrayList<Cell> cells = prepareData();
ImageAdapter adapter = new ImageAdapter(getApplicationContext(), cells);
recyclerView.setAdapter(adapter);
}
private ArrayList<Cell> prepareData(){
ArrayList<Cell> allImages = new ArrayList<>();
for (Cell c : allFilesPaths){
Cell cell = new Cell();
cell.setTitle(c.getTitle());
cell.setPath(c.getPath());
allImages.add(cell);
}
return allImages;
}
private List<Cell> listAllFiles(String pathName){
List<Cell> allFiles = new ArrayList<>();
if(pathName != null){
File file = new File(pathName);
File[] files = file.listFiles();
if(files != null){
for (File f : files){
Cell cell = new Cell();
cell.setTitle(f.getName());
cell.setPath(f.getAbsolutePath());
allFiles.add(cell);
}
}
}
return allFiles;
}
Inside my Image Adapter :
private ArrayList<Cell> galleryList;
private Context context;
private static final String TAG = "ImageAdapter";
public ImageAdapter(Context context, ArrayList<Cell> galleryList) {
this.context = context;
this.galleryList = galleryList;
}
#NonNull
#Override
public ImageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell, parent, false);
return new ImageAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ImageAdapter.ViewHolder holder, final int position) {
holder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
Log.d(TAG, "onBindViewHolder: " + galleryList.size());
setImageFromPath(galleryList.get(position).getPath(), holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path = galleryList.get(position).getPath();
Intent intent = new Intent(context ,ImagePreview.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("imagePath",path);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView img;
public ViewHolder(#NonNull View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img);
}
}
private void setImageFromPath(String path, ImageView image){
File imgFile = new File(path);
try {
Bitmap myBitmap = BitmapFactory.decodeStream(new FileInputStream(imgFile));
image.setImageBitmap(myBitmap);
// ImageView imageView = (ImageView)findViewById(R.id.imageViewSelect);
// imageView.setImageBitmap(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
method inside drawing activity that saves images :
public void saveImage() {
ContextWrapper cw = new ContextWrapper(getContext());
String filename = "img" + System.currentTimeMillis();
File directory = cw.getDir("files", Context.MODE_PRIVATE);
path = cw.getDir("files", Context.MODE_PRIVATE).toString();
File myPath = new File(directory, filename + ".jpg");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(myPath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
Make sure the variable DrawingActivity.path in showImages() have some value inside of it. It might not have initialized properly.
Try putting this in the ViewHolder Class constructor instead
setImageFromPath(galleryList.get(getLayoutPosition()).getPath(), holder.img);

Set dynamic image to ListView in android custom adapter

i am building a listview with items from web server. I got all the items with JSON, i am able to load all the text values to the list view, but i can't assign the image to the list item. when i access a static image from drawable folder it works. Here is my code. I have the image with Base64 and direct file URL.
int[] listviewImage = new int[]{R.drawable.food};
JSONObject reader = new JSONObject(result);
JSONArray foods= reader.getJSONArray("foods");
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for(int i = 0;i<foods.length();i++)
{
JSONObject obj_foods = foods.getJSONObject(i);
HashMap<String, String> hm = new HashMap<String, String>();
byte[] decodedString = Base64.decode(obj_foods .getString("photo_hex"), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
hm.put("listview_image", Integer.toString(listviewImage[0]));
hm.put("food_name", obj_foods .getString("food_name"));
hm.put("food_description",obj_foods .getString("food_description"));
hm.put("price",obj_foods .getString("price"));
hm.put("restaurant",obj_foods .getString("restaurant"));
aList.add(hm);
}
String[] from = {"listview_image", "food_name", "food_description","price","restaurant"};
int[] to = {R.id.listview_image, R.id.listview_item_title, R.id.listview_item_short_description,R.id.price,R.id.restaurant};
SimpleAdapter simpleAdapter = new SimpleAdapter(getBaseContext(), aList, R.layout.food_list, from, to);
final ListView androidListView = (ListView) findViewById(R.id.listview);
androidListView.setAdapter(simpleAdapter);
Use Picasso to fetch images from online to your app
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);

How to set images from assets folder to list view?(using SimpleAdapter)

I've got folder in assets called images1 with 114 images in it. I need to set them in listView with 2 textViews and 1 imageView. I haven't problems with textViews, but i don't know how to set images from assets to listView.
I tried:
int ids[] = new int[114];
for (int i = 0; i <ids.length; i++) {//<-------- taking ids of all pictures from images1 in assets-folder
try {
String[] images =getAssets().list("images1");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));
int imgId = getResourceId(this, listImages.get(i),"images1", getPackageName());
ids[i] = imgId;
}
catch(IOException ex) {}
}
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
questionTexts.length);//<--------filling listView's textViews and imageView
Map<String, Object> m;
for (int i = 0; i < questionTexts.length; i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_QUESTION_TEXT, questionTexts[i]);//<-------- textView
m.put(ATTRIBUTE_ANSWER_TEXT, answerTexts[i]);//<-------- textView
m.put(ATTRIBUTE_NAME_IMAGE, ids[i]);//<-------- imageView
data.add(m);
String[] from = { ATTRIBUTE_QUESTION_TEXT, ATTRIBUTE_ANSWER_TEXT,
ATTRIBUTE_NAME_IMAGE };
int[] to = { R.id.listView_item_title, R.id.listView_item_short_description, R.id.listView_image };
SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.item,
from, to);
lvSimple = (ListView) findViewById(R.id.lvSimple);
lvSimple.setAdapter(sAdapter);
}
public static int getResourceId(Context context,String variableName, String resourceName,
String packageName) throws RuntimeException{//<----- this method helps me to get IDs of images from assets/images1
try{
return context.getResources().getIdentifier(variableName,resourceName,packageName);
}catch (Exception e){
throw new RuntimeException("Error getting resource id");
}
}
But finally i've got white fields instead my pictures.
I know how to solve this problem when your pictures are in R.drawable, but how to do it when they are in assets subfolder?
You can use this.
try
{
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
ims .close();
}
catch(IOException ex)
{
return;
}
Are you sure that this images should be inside assets/ folder? Why not in res/drawables/?
Of course you can load it from assets ;)
To get the list of all files inside asset folder use below code:
list = getAssets().list("images1")
To load the image from asset you can use below code:
fun setImageFromAsset(ImageView view, String filename) {
try {
InputStream is = getAssets().open(filename);
Drawable drawable = Drawable.createFromStream(is, null);
view.setImageDrawable(drawable);
}
catch(IOException ex) {
return;
}
}
You can get a bitmap by using below code
private Bitmap getBitmapFromAssets(String fileName){
AssetManager am = getAssets();
InputStream is = null;
try{
is = am.open(fileName);
}catch(IOException e){
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
You can show bitmap in imageview by using "Glide" Here is sample code
Glide.with(context)
.load(Uri.parse("file:///android_asset/fileName"))
.into(imageView);
Simple Adapter can work only with IDs in drawable-folder or with Uri. But you can use ViewBinder to set image using setImageBitmap method.

java.lang.OutOfMemoryError on storing images in sqlite db

I want to store images in my database. Also I want to check that if the image and title is already in the database. If so, it will not add them to the database. This is my class.
Attractions
public class Attractions extends ListActivity {
DataBaseHandler db = new DataBaseHandler(this);
ArrayList<Contact> imageArry = new ArrayList<Contact>();
List<Contact> contacts;
ContactImageAdapter adapter;
int ctr, loaded;
int [] landmarkImages={R.drawable.oblation,R.drawable.eastwood,R.drawable.ecopark,R.drawable.circle};
String []landmarkDetails = { "Oblation", "Eastwood", "Ecopark", "QC Circle"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attractions);
ctr = db.checkContact(landmarkDetails[loaded]);
// get image from drawable
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
for(loaded=0; loaded <landmarkDetails.length;loaded++){
Bitmap image = BitmapFactory.decodeResource(getResources(),
landmarkImages[loaded]);
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.d("Going to load images", "Image "+ loaded);
Log.d("Goind to load objects", "loading");
if(ctr == 0){
Log.d("Nothing Loaded", "Loading Now");
db.addContact(new Contact(landmarkDetails[loaded], imageInByte));}
Log.d(landmarkDetails[loaded], "Loaded!");
image.recycle();
}
loadFromDb();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.attractions, menu);
return true;
}
public void loadFromDb(){
// Reading all contacts from database
contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage();
// Writing Contacts to log
Log.d("Result: ", log);
//add contacts data in arrayList
imageArry.add(cn);
}
adapter = new ContactImageAdapter(this, R.layout.screen_list,
imageArry);
ListView dataList = (ListView) findViewById(android.R.id.list);
dataList.setAdapter(adapter);
}
public void onPause(){
super.onPause();
}
public void onResume(){
super.onResume();
}
}
It works fine on the emulator, but I tried testing on my S4 and then after 3 tries of going to this class, it forced stop. I tried it with usb debugging and the logcat showed java.lang.outofmemoryerror . The logcat pointed the error in my contactimageadapter.
ContactImageAdapter
public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
// BcardImage data[] = null;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
//convert byte to bitmap take from contact class
byte[] outImage=picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
And pointed to this line Bitmap theImage = BitmapFactory.decodeStream(imageStream);
I have little (almost none) knowledge on managing images and storing them. I also enable android:largeHeap but still force closes on multiple tries. I hope someone can help me solving this issue, or at least show me a different way of storing text and images to sqlite db. Many thanks!
You have multiple places where whole image (assuming it is big) keeps in memory:
Contact object has it. All loaded images are in imageArry which is instance level variable.
public class Attractions extends ListActivity {
DataBaseHandler db = new DataBaseHandler(this);
ArrayList<Contact> imageArry = new ArrayList<Contact>();
in ContactImageAdapter.getView method you create another copy of image as BMP in holder object and pass it out of method.
So, at some point you do not have enough memory to keep all of them. Also I sure that decodeStream needs some more memory to perform.
After all it is not predictable when each new holder created in getView will be cleaned by GC.
Usually for such situation when object created as new in some method, then passed back to the calling method, that object will be collected only by Full GC.
So, as "Software Sainath" said, do not store images in database…
and do not keep them in memory either.
P.S. Then provide to the view a link to the external image file. That also will save time to load a view. Image will be in cache and if user at least once got it, it will not pass through the network again.
I guess images there are not frequently change them self. another image of Contact will be another file…
I wrote an answer to the somewhat similar problem some while ago, here is the link that you can check. The problem is in the approach of saving the images into the database, you should not be doing this. Instead, write the images as files on the phone memory and use it further.
Don't store Image to Sqlite Database eventually, you will ran into out of memory error after three or five image saved to database. It's not the best practice, maximum memory allocated for field in a row in sqlite is less than 3mb, be aware of this.
Instead of saving Images to database, Keep the images inside your app folder, save the path to the Database.
Your are loading your image as it is to your Image adapter. Let's say your image is 1280x720 resolution and 2mb in size, it will take the same space in your memory Heap.
You can either scaledown your image and load it as bitmap to your Adapter ImageView like this.
Before loading your image as Bitmap get it height and width.
//Code read the image and give you image height and width.it won't load your bitmap.
BitmapFactory.Options option = new BitmapFactory.Options();
option.inJustDecodeBounds = true;
BitmapFactory.decodeFile(your_image_url,option);
int image_original_width = option.outHeight;
int image_original_height = option.outWidth;
Now to scale down your Image you have to know the ImageView width and height. This is because we are going to scale down the image matching the imageview with pixel perfection.
int image_view_width = image_view.getWidht();
int image_view_height = image_view.getHeight();
int new_width;
int new_height;
float scaled_width;
if(image_original_width>image_view_width)
{ //if the image_view width is lesser than original_image_width ,you have to scaled down the image.
scale_value =(float)image_original_width/(float)image_view_width;
new_width = image_original_width/scaled_value;
new_height = image_orignal_height/scale_value
}
else
{
// use the image_view width and height as sacling value widht and height;
new_width = image_view_width;
new_height = image_view_height;
}
Now Scale Down your bitmap and load it like this.
// this will load a bitmap with 1/4 the size of the original one.
// this to lower your bitmap memory occupation in heap.
BitmapFactory.Options option = new BitmapFactory.Options();
option.inSampleSize = 4;
Bitmap current_bitmap = BitmapFactory.decodeFile(image_url,option);
Bitmap scaled_bitmap = Bitmap.createScaledBitmap(current_bitmap,new_width,new_height,true);
holder.imgIcon.setImageBitmap(scaled_bitmap);
//release memory occupied by current_bitmap in heap, as we are no longer using it.
current_bitmap.recycle();
If you want to understand a little more about Bitmap and memory view this link.
If you don't want to handle rescaling bitmap by yourself. you can use Glide or Picasso library which does the same.
I have written an article about using Picasso to load image in listview, which will help you to start, if you are looking to use picasso.
http://codex2android.blogspot.in/2015/11/picasso-android-example.html
Please make sure to use the quick garbage collection eligible reference type while loading the images from the network
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;
public class MemoryCache {
private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
public Bitmap get(String id){
if(!cache.containsKey(id))
return null;
SoftReference<Bitmap> ref=cache.get(id);
return ref.get();
}
public void put(String id, Bitmap bitmap){
cache.put(id, new SoftReference<Bitmap>(bitmap));
}
public void clear() {
cache.clear();
}
}
Don't store Image to Sqlite Database. It's not the best practice.
Instead of saving Images to database, Keep the images in a storage, but if you want to keep them private then keep them inside your app folder and save the path to the Database.
Use one of the well known libraries like http://square.github.io/picasso/ or https://github.com/bumptech/glide, they offer great help with memory issues and also some cool transition effects.
I recommend using Glide because it works very well on device with low memory restrictions

Android - How to show images from SDcard android Use ImageGetter

Hi guys i have problem i need show image in EditText use : ImageGetter.
this work
String html = "<img src=\"ic_launcher\">";
CharSequence text = Html.fromHtml(html, new Html.ImageGetter(){
public Drawable getDrawable(String source){
int id = getResources().getIdentifier(source, "drawable", getPackageName());
Drawable d = getResources().getDrawable(id);
int w = d.getIntrinsicWidth();
int h = d.getIntrinsicHeight();
d.setBounds(0, 0, w, h);
return d;
}
}, null);
mContentEditText.setText(text);
but i need my image in SDcard ,not "R.drawable.IMAGE_NAME" ,Thanks
You have to apply the appropriate permissions in the manifest so that you can read from external storage. Then create a piece of code that will search your SD Card for the image you want.
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
Where imageFile is your ImageFile, for example: File imageFile = new File("/sdcard/gallery_photo_4.jpg");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPath ="Your image Path here";
l1=(LinearLayout) findViewById(R.id.layout1);
l1.setBackgroundColor(Color.WHITE);
System.out.println(mPath);
Bitmap b=Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mPath),l1.getWidth(),l1.getHeight(),false);
if(b!=null){
ImageView iv=new ImageView(this);
iv.setImageBitmap(b);
l2.addView(iv);
}
}
Here is the code which works for me.hope it will help you.
String html2 = "<img src=\"a.jpg\">";
CharSequence text2 = Html.fromHtml(html2, new Html.ImageGetter(){
public Drawable getDrawable(String source){
String path = "/sdcard/a/" + source;
File f = new File(path);
Drawable bmp = Drawable.createFromPath(f.getAbsolutePath());
bmp.setBounds(0, 0, bmp.getIntrinsicWidth(), bmp.getIntrinsicHeight());
return bmp;
}
}, null);
display.setText(text2);
is Work for me! 100% thx all :)

Categories

Resources