I tried to store a BitMap in the database as Base64 string, but somehow I just cant preview it in the ImageView. Here's the code:
Store Data:
Map params = new HashMap();
params.put("faasid", faasid);
params.put("title", data_title);
params.put("image", Base64.encodeToString(DbBitmapUtility.getBytes(bitmap),Base64.DEFAULT));
ImageDB db = new ImageDB();
db.create(params);
Retrieve Data:
List<ImageItem> data = new ArrayList<ImageItem>();
Map params = new HashMap();
params.put("faasid", faasid);
ImageDB db = new ImageDB();
List<Map> list = db.getList(params);
for(Map m : list){
String title = m.get("title") != null ? m.get("title").toString() : "";
String image = m.get("image") != null ? m.get("image").toString() : "";
data.add(new ImageItem(faasid, title, image.getBytes()));
}
image_list.setAdapter(new ImageItemAdapter(activity,data));
LayoutParams layout = (LayoutParams) image_list.getLayoutParams();
layout.height = (320 * data.size());
image_list.setLayoutParams(layout);
ImageItem.java:
public class ImageItem {
private String faasid, title;
private byte[] image;
public ImageItem(String faasid, String title, byte[] image){
this.faasid = faasid;
this.title = title;
this.image = image;
}
public String getFaasId(){ return faasid; }
public String getTitle(){ return title; }
public Bitmap getImage(){ return DbBitmapUtility.getImage(image); }
}
DbBitmapUtility.java
public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 80, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
ImageItemAdapter.java (my custome ListView adapter)
public class ImageItemAdapter extends BaseAdapter{
LayoutInflater inflater = null;
Context ctx;
List<ImageItem> data;
public ImageItemAdapter(Activity activity, List<ImageItem> data){
ctx = activity;
this.data = data;
inflater = ( LayoutInflater )ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int pos) {
return pos;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View view, ViewGroup vgroup) {
View rowView = inflater.inflate(R.layout.image_menu, null);
ImageView image = (ImageView) rowView.findViewById(R.id.image_menu_view);
TextView title = (TextView) rowView.findViewById(R.id.image_menu_text);
ImageItem item = data.get(pos);
if(item != null){
image.setImageBitmap(item.getImage());
title.setText(item.getTitle());
}
return rowView;
}
public ImageItem getListItem(int pos){
return data.get(pos);
}
I print the result of this code: List list = db.getList(params);, and there was data in it, but the problem is: The image wont appear in the ImageView.
The problem is you encode your image into a Base64 String, but you never actually decode it.
For the decoding:
String encodedBytes = params.get("image");
byte[] decodedBytes = Base64.decode(encodedBytes, Base64.DEFAULT);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
The actual flow should be something like this:
Bitmap -> byte array -> Base64 encoded String -> To DB.
From DB -> Base64 encoded String -> decoded byte array -> decoded Bitmap.
Related
i Was try to display image to card view but it not working and do not show error. Anyone help me please. I am new android. i checked file exists from downloaded folder: /storage/emulated/0/hismart/hinhmon
public class Album {
private String name;
private String gia;
private String thumbnail;
private String url;
public Album() {
}
public Album(String name, String gias, String thumbnail, String url) {
this.name = name;
this.gia = gias;
this.thumbnail = thumbnail;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGia() {
return gia;
}
public void setGia(String gia) {
this.gia = gia;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Creat and add data to ArrayList:
List<String> ArrTenmon = new ArrayList<String>();
List<String> ArrGia = new ArrayList<String>();
List<String> ArrImgLocal = new ArrayList<String>();
List<String> ArrImgUrl = new ArrayList<String>();
and add
} Cursor c = db.getdata("select * from tbl_mon_app");
int count = c.getCount();
for (int i = 0; i < count; i++) {
new DownloadFile().execute(ArrImgUrl.get(i));
if (!fileloc.exists()) {
fileloc.mkdirs();
}
Album a = new Album(ArrTenmon.get(i), ArrGia.get(i), ArrImgLocal.get(i), ArrImgUrl.get(i));
albumList.add(a);
adapter.notifyDataSetChanged();
}
and in adapter:
String folder_main = "hismart/hinhmon";
File fileloc = new File(Environment.getExternalStorageDirectory(), folder_main);
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public AlbumsAdapter(Context mContext, List<Album> albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Album album = albumList.get(position);
holder.title.setText(album.getName());
holder.count.setText(album.getGia() + " vnđ");
File imgFile = new File(fileloc+"/"+ "album" + position);
Glide.with(mContext).load(imgFile).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return albumList.size();
}
And Problem in bellow can not display image, name of image is: album1, alubm2...
File imgFile = new File(fileloc+"/"+ "album" + position);
Glide.with(mContext).load(imgFile).into(holder.thumbnail);
Download file:
class DownloadFile extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog = new ProgressDialog(BookActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
String targetFileName = null;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
targetFileName = aurl[0].substring(aurl[0].lastIndexOf("/") + 1);
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/hismart/hinhmon/";
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH + targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return targetFileName;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if (mProgressDialog.getProgress() == mProgressDialog.getMax()) {
mProgressDialog.dismiss();
}
}
protected void onPostExecute(String result) {
}
}
call asyntask to download file
Cursor c = db.getdata("select * from tbl_mon_app");
int count = c.getCount();
for (int i = 0; i < count; i++) {
new DownloadFile().execute(ArrImgLocal.get(i));
if (!fileloc.exists()) {
fileloc.mkdirs();
}
}
Logcat: Show nothing error
Result like this:image after run
I am sure Glide code which you used will works, i have used it many project. There might be problem in your image file. Cross check all the points Sd card permissions, file path use are getting correct
if not worked try to convert file to Uri, it may help
File imgFile = new File(fileloc+"/"+ "album" + position);
Uri imageUri = Uri.fromFile(file);
Glide.with(this).load(imageUri).into(imgView);
Hello I am using listview and display images from server into it.
But the problem is that all loaded images are displayed in last item one by one instead display on respective position.
please help me to display that images in respective position
public class Offer_adapter extends ArrayAdapter<String> {
Context context1;
String[] offer_title;
String[] offerimg1;
String[] mrp;
String[] offerprice;
String[] you_save;
String[] imgURLArray;
Bitmap bitmap;
ImageView offerimg;
int a;
LayoutInflater inflater1;
public Offer_adapter(Context context1, String[] offer_title, String[] offerimg1, String[] mrp, String[] you_save, String[] offerprice) {
super(context1, R.id.offer_list, offer_title);
this.context1 = context1;
this.offer_title = offer_title;
this.offerimg1 = offerimg1;
this.mrp = mrp;
this.offerprice = offerprice;
this.you_save = you_save;
}
private static class ViewHolder {
String offerimg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
inflater1 = (LayoutInflater) context1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater1.inflate(R.layout.offer_list, null);
viewHolder = new ViewHolder();
}
android.util.Log.v("abhi", "" + position);
imgURLArray = new String[position + 1];
for (int i = 0; i <= position; i++) {
android.util.Log.v("abhijit", "" + position);
imgURLArray[i] = "http://www.surun.co/preost/mod_offer/images/" + offerimg1[position];
android.util.Log.v("abhi", "" + imgURLArray[position]);
}
a=position;
viewHolder = (ViewHolder) convertView.getTag();
TextView offertitle = (TextView) convertView.findViewById(R.id.ofrtitle);
TextView offermrp = (TextView) convertView.findViewById(R.id.offeroriginal);
offermrp.setPaintFlags(offermrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offersave = (TextView) convertView.findViewById(R.id.saveoffer);
TextView ofrprice = (TextView) convertView.findViewById(R.id.priceoffer);
offerimg = (ImageView) convertView.findViewById(R.id.ofr_img);
offertitle.setText(offer_title[position]);
offermrp.setText("Original Price: \u20B9" + mrp[position]);
offersave.setText("You Save: \u20B9" + you_save[position]);
ofrprice.setText("Offer Price: \u20B9" + offerprice[position]);
// Bitmap imageBitmap = null;
new DownloadAsyncTask().execute(imgURLArray[position]);
Log.v("abhi","async");
return convertView;
}
private class DownloadAsyncTask extends AsyncTask<String, String, Bitmap> {
protected Bitmap doInBackground(String... args) {
try {
Log.v("abhi","in do background");
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, 270, 375, true);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap !=null) {
offerimg.setImageBitmap(bitmap);
} else {
offerimg.setImageResource(R.drawable.nooffer);
}
}
}
}
All images are shown in last item one after another. I just want to show it on respective position.
you should use lazyloading instead of downloading image as bitmap.
Bitmap will create problem sometime or will give you outofmemory error in some devices
There are lots of image loading library available for android.
Have a look at these
https://github.com/square/picasso
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading
https://android.googlesource.com/platform/frameworks/volley
https://github.com/koush/UrlImageViewHelper
https://github.com/novoda/image-loader
After I decided to implement Universal Image Loader, because I had implemented a method that convert URL to Drawable, but since I don't know how many images it will return my SQLite query I decided to implement an Image Loader...
The thing is I'm stuck at the moment, cause I thought I did all what the GitHub say but at the time I load the Image it stays white and never loads.
On my Adapter class I've changed the line of the drawable as :
Picasso.with(context)
.load(Uri.parse(String.valueOf(item.icon)))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
It works, beucase it shows yo me the ic_launcher icon... but never changes to the real image.
On my class where I fetch the data I have this (on my OnCreate()) :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new MyAsyncTask().execute();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// progress.dismiss();
}
});
}
}).start();
}
Then I created an inner class where I fetch the data into my ListView... but it doesn't works. I don't know If I've to delte those methods since I've changed it to Picasso.
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Conexion = new MarketSQLite(getActivity(), "market", null, 1);
mItems = new ArrayList<ListViewItem>();
db = Conexion.getReadableDatabase();
Cursor c;
c = db.rawQuery("Select NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
FOTO = Imagehandler(URLTest);
Log.e("", "" + c.getString(i));
// initialize and set the list adapter
// Toast.makeText(getActivity(), "Title" + Title + "Preu" + Preu + "Percent" + percent + "Cheese is " + data_f, Toast.LENGTH_LONG).show();
}
mItems.add(new ListViewItem(FOTO, Title, Preu.toString(), percent, data_f));
}while (c.moveToNext());
}
c.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
myAdapter = new ListViewDemoAdapter(getActivity(), mItems);
setListAdapter(myAdapter);
}
}
Where ImageHandler is a method that I've created before this is :
protected Drawable Imagehandler(String url) {
try {
url=url.replaceAll(" ", "%20");
InputStream is = (InputStream)this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e)
{
System.out.println(url);
System.out.println("error at URI"+e);
return null;
}
catch (IOException e)
{
System.out.println("io exception: "+e);
System.out.println("Image NOT FOUND");
return null;
}
}
protected Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
I don't know why isn't the image loading on my ListView if it shows all of the rest of data...
Instead of Drawable, try to get url string in your adapter like
Change From
public ListViewItem(Drawable icon, String title, String precio, String descuento, String date) {
this.icon = icon;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
To
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon_url = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
and use Picasso where you are loading your imageview like this -
Picasso.with(context)
.load(icon_url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
1) Your ListViewItem class should be like this -
public class ListViewItem {
public final String icon; // the drawable for the ListView item ImageView
public final String title; // the text for the ListView item title
public final String precio; // the price for the ListView item
public final String descuento; // the price for the discount for the ListView item
public final String date; //the date for the sale for the ListView item
// the text for the ListView item description
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
}
2) ListViewDemoAdapterClass
public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> {
Context context;
public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
super(context, R.layout.listview_item, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_item, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
viewHolder.tvDiscount = (TextView) convertView.findViewById(R.id.tvDiscount);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDatas);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListViewItem item = getItem(position);
Picasso.with(context)
.load(item.icon)
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
viewHolder.tvTitle.setText(item.title);
viewHolder.tvDiscount.setText(item.descuento);
viewHolder.tvPrice.setText(item.precio);
viewHolder.tvDate.setText(item.date);
return convertView;
}
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDiscount;
TextView tvPrice;
TextView tvDate;
}
}
ListFragment code, just add this
Cursor c;
c = db.rawQuery("Select
NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
Hope this helps :)
you just need to add your picasso code snippet as the following in your ImageHandler method and nothing else-
Picasso.with(context)
.load(url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(your_imageview);
you don't need to download the image or make the bitmap or convert that into drawable to load from url. hope this helps you.
I'm 3 days ago now looking for an answer and find no satisfying.
I created a listview to populate it with a picture and a text, the way the image is saved in sqlite database and image is in sd card of the phone, but only that not all rows from the database has a path to image so I'm placing a default image, but the problem is that even the images that are the path, not returning to this image, follows my adapter code below:
public class AgendaListAdapter extends ArrayAdapter<Agenda> {
private LayoutInflater inflater;
private List<Agenda> lista;
private Agenda agenda;
int resources;
//constructor
public AgendaListAdapter(Context context, int resource, List<Agenda> lista){
super(context, resource, lista);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resources = resource;
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Agenda getItem(int position) {
return lista.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
agenda = lista.get(position);
//cria uma referencia para viewHolder
//creates a reference to
ViewHolder viewHolder;
//verifica se a view esta sendo reusada ou não
//verifies that the view is being reused or not
if(convertView == null){
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.linha_listar_telefones, null);
viewHolder.mNome = (TextView) convertView.findViewById(R.id.nome);
viewHolder.mImagem = (ImageView) convertView.findViewById(R.id.listar_contato_imagem);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
if(agenda != null){
if(viewHolder.mNome != null){
viewHolder.mNome.setText(agenda.nome);
}
if(viewHolder.mImagem != null){
viewHolder.mImagem.setTag(lista.get(position));
Log.w("Livro", "Positiom: "+position);
Log.e("Livro", "Viewhol.imagem não é nulo "+viewHolder.mImagem);
new loadImageTask(viewHolder.mImagem).execute();
}
}
return convertView;
}
private static class ViewHolder{
protected TextView mNome;
protected ImageView mImagem;
}
Bitmap b = null;
private class loadImageTask extends AsyncTask<Agenda, Void, Bitmap>{
private ImageView imv;
private String path;
public loadImageTask(ImageView imv) {
this.imv = imv;
this.path = agenda.caminho_imagem;
}
#Override
protected Bitmap doInBackground(Agenda... params) {
Log.w("Livro", "path: "+path);
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
b = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return b;
}
#Override
protected void onPostExecute(Bitmap result) {
if(result != null && imv != null){
Log.i("Livro", "Result do onPostExcute não é nulo: "+result);
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
Log.i("Livro", "Result do onPostExcute é nulo: "+result);
imv.setImageResource(R.drawable.foto_pessoa);
}
}
}
}
In the logcat path returning this: content ://media/external/images/media/16
The variable file is returning the following result: / storage/emulated/sdcard0content ://media/external/images/media/16
I know the result of this wrong file, but would transform into uri path and pass a uri to file?
Thanks guys!!!
The path //media/external/images/media/16 is a Media Uri...You have to get the actual file path from the Uri and then set the image to the ImageView.
Get the real file path from Media Uri as below and the returned path is absolute file path...
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Get Bitmap from the path returned by getRealPathFromURI() method as below...
Context mContext;
public loadImageTask(Context context, ImageView imv) {
this.mContext = context;
this.imv = imv;
this.path = agenda.caminho_imagem;
}
#Override
protected Bitmap doInBackground(Agenda... params) {
Log.w("Livro", "path: "+path);
File file = new File(getRealPathFromURI(mContext, path));
if(file.exists()){
b = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return b;
}
And pass the context of the activity through the asynctask constructor as below...
new loadImageTask(context, viewHolder.mImagem).execute();
When I start my application I have a Asynctask kick off which looks for any new videos and creates the thumbnails and adds them to a database. I later use the Universal Image Loader to find and set that bitmap to the view. My problem is when I start my application for the first time all the data is loaded to the database but nothing shows up in the gridview. I don't even think the adapter gets called. However, when I start the application once all the data is loaded the gridview shows all the thumbnails and it runs smoothly.
I was wondering why this happens and what I could do to fix this problem. My code is below
AsyncTask
private class DataEntry extends AsyncTask<Void, Integer, GridviewData>{
GridviewData dataentry;
DataEntry(GridviewData gridviewdata){
this.dataentry = gridviewdata;
}
#Override
protected GridviewData doInBackground(Void... params) {
cursor.moveToFirst();
do {
String videoid = cursor.getString(columnindexid);
String videopath = cursor.getString(columnindexdata);
int result = dataentry.findVideoID(videoid);
if (result == 1){
Bitmap bmthumb = ThumbnailUtils.createVideoThumbnail(videopath, MediaStore.Video.Thumbnails.MINI_KIND);
if (bmthumb != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmthumb.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] thumbnailBitmapBytes = stream.toByteArray();
dataentry.addVideoinfo(videoid, videopath, thumbnailBitmapBytes);
}
}
if (result == 0){
Log.i(TAG, "Cursor wasn't processed, no getcount");
}
if(result == 2){
//there is data already there
}
} while (cursor.moveToNext());
Log.i(TAG, "After dowhile loop");
cursor.close();
return dataentry;
}
}
Base Image Loader
public class SqliteImageDownloader extends BaseImageDownloader {
private static final String SCHEME_DB = "db";
private static final String DB_URI_PREFIX = SCHEME_DB + "://";
Cursor cursor;
public SqliteImageDownloader(Context context) {
super(context);
}
#Override
protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException {
if (imageUri.startsWith(DB_URI_PREFIX)) {
String path = imageUri.substring(19);
cursor = entry.BitFinder(path);
byte[] imageData = cursor.getBlob(0);
return new ByteArrayInputStream(imageData);
} else {
return super.getStreamFromOtherSource(imageUri, extra);
}
}
}
Cursor Adapter
class VideoAdapter extends CursorAdapter {
Cursor curs;
Context context;
public VideoAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
this.curs = c;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
String filepath = curs.getString(videopathindex);
ImageLoader.getInstance().displayImage("db://VideoandThumbs" + filepath, holder.imageview);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View eachgrid = inflater.inflate(R.layout.eachgrid, parent, false);
ViewHolder holder = new ViewHolder();
holder.imageview = (ImageView) eachgrid.findViewById(R.id.Imageview1);
eachgrid.setTag(holder);
return eachgrid;
}
}