I want to send image from list view to other activity. I think i've done most of job, but i am continiously getting nullpointerexeptioon. Seems that my bitmap is null. How can i pass image from choosen item as a resourse to bitmap?
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
ImageView imm_id = ((ImageView) arg1.findViewById(R.id.imagePrev));
imm_id.getId();
RequestDataHolder.request_id = ids.get(position);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(), imm_id.getId());
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] imm=stream.toByteArray();
Intent i = new Intent(getApplicationContext(),ResultViewActivity.class);
i.putExtra("imMap", imm);
startActivity(i);
adapter
public class MediaItemAdapter extends SimpleAdapter {
private int[] colors = new int[] { 0x30FF0000, 0x300000FF };
public static boolean notifyFlag = false;
private Context localContext;
private List<HashMap<String, Object>> locallist;
private static LayoutInflater inflater=null;
private Object rslv;
public ImageView imgV;
public String valueV;
Map cache = new HashMap();
public MediaItemAdapter(Context context,
List<HashMap<String, Object>> items, int resource,
String[] from,
int[] to) {
super(context, items, resource, from, to);
localContext = context;
locallist = items;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void setViewText(TextView v, String text) {
// метод супер-класса, который вставляет текст
super.setViewText(v, text);
{
v.setText(Html.fromHtml(text));
}
}
#Override
public void setViewImage(ImageView v, String value) {
imgV = v;
valueV = value;
super.setViewImage(v, value);
if (imgV.getId() == R.id.imagePrev) {
if (value == null || value.trim().length() <= 0
|| value.equalsIgnoreCase("null")
|| value.trim().equalsIgnoreCase("")) {
imgV.setImageResource(R.drawable.stub);
// do nothing
} else {
if (cache.get(value) == null
&& !SearchPostActivity.loadingMore) {
notifyFlag = false;
new LazyImageLoader(localContext, value).execute();
} else {
imgV.setImageBitmap((Bitmap) cache.get(value));
}
}
}
}
class LazyImageLoader extends AsyncTask<String, Integer, Bitmap> {
private String URL;
private Context context;
public LazyImageLoader(Context context, String Url) {
URL = Url;
LazyImageLoader.this.context = context;
}
#Override
protected void onPreExecute() {
imgV.setImageResource(R.drawable.home);
}
#Override
protected Bitmap doInBackground(String... params) {
return getImg();
}
#Override
protected void onPostExecute(Bitmap img) {
if (!SearchPostActivity.scrollFlag) {
imgV.setImageBitmap(img);
notifyDataSetChanged();
}
notifyFlag = true;
cache.put(URL, img);
}
public synchronized Bitmap getImg() {
Bitmap bm = null;
try {
URL myurl;
myurl = new URL(URL);
URLConnection conn = myurl.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
bm = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_composer, null);
ImageView thumb_image=(ImageView)vi.findViewById( R.id.imagePrev);
return vi;
}
}
try this
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, final View view, final int position, final long id) {
final ImageView imageView = (ImageView) view.findViewById(R.id.imageViewXYZ);
final BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
}
});
it would be better to use debug tool to find out the values of getResources() and imm_id.getId() at
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),imm_id.getId());
Related
I have a listview which is showing some images. To avoid UI blocks, I tried to lazy load the thumbnails with an asyncTask in my adapter since that seemed the best solution I found here on SO.
This listView has also an onItemclick and an onItemLongClick listeners.
For some reason, my app is getting really slow down, expecially after performing an onlongclick action. The only thing I found unusual is that my ListView is calling the getView method in loop, never stopping.
Some code:
Adapter
public class FotoGridAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList<WorkorderPicture> workorderPictures = new ArrayList<WorkorderPicture>();
public FotoGridAdapter(Context context, int layoutResourceId, List<WorkorderPicture> pictures) {
super(context, layoutResourceId, pictures);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.workorderPictures = new ArrayList<>(pictures);
}
#Override
#Nullable
public WorkorderPicture getItem(int position) {
return workorderPictures.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = row.findViewById(R.id.text);
holder.image = row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
WorkorderPicture workorderPicture = workorderPictures.get(position);
if (workorderPicture != null) {
String text = workorderPicture.getTITLE();
if (workorderPicture.getPHOTODATE() != null) {
text += " - ";
text += new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(workorderPicture.getPHOTODATE());
}
holder.imageTitle.setText(text);
String format = AttachmentUtils.getExtensionFromFileName(workorderPicture.getFILE_NAME_WITH_EXTENSION());
if (format == null)
format = "default";
switch (format.toLowerCase()) {
case "image/jpeg":
case "image/png":
if (workorderPicture.getPHOTOSTREAM() != null) {
new ImageGridHandler(context, holder.image, workorderPicture.getPHOTOSTREAM(), workorderPicture.getPHOTOSTREAM().length).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// holder.image.setImageBitmap(sbm);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.setImageDrawable(getContext().getDrawable(R.drawable.ic_image));
} else {
holder.image.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_image));
}
}
break;
case "application/pdf":
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.setImageDrawable(getContext().getDrawable(R.drawable.ic_pdf));
} else {
holder.image.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_pdf));
}
break;
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.setImageDrawable(getContext().getDrawable(R.drawable.ic_empty_image));
} else {
holder.image.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_empty_image));
}
break;
}
}
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
class ImageGridHandler extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private Context context;
private byte[] photoStream;
private int length;
public ImageGridHandler(Context context, ImageView img, byte[] photoStream, int length) {
imageViewReference = new WeakReference<>(img);
this.context = context;
this.photoStream = photoStream;
this.length = length;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bm = BitmapFactory.decodeByteArray(photoStream, 0, length);
return ThumbnailUtils.extractThumbnail(bm, 80, 100);
}
#Override
protected void onPostExecute(Bitmap result) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
FotoGridAdapter.this.notifyDataSetChanged();
}
this.cancel(true);
}
}
}
Listeners
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
final int position, long l) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.myAlertDialogTheme)
.setNegativeButton("Annulla", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.setPositiveButton("Elimina", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String wpID = openedIntervention.getWorkorderPictures().get(position).getID();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.where(WorkorderPicture.class).equalTo("ID", wpID).findFirst().setDELETED(true);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
openedIntervention.setWorkorderPictures(realm.where(WorkorderPicture.class)
.equalTo("WORKORDER_ID", openedIntervention.getWorkorder()
.getID())
.equalTo("DELETED", false)
.findAll());
loadData();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
});
}
}).setTitle(app_name)
.setMessage("Eliminare l'allegato selezionato?");
builder.show();
return true;
}
});
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) {
//code to show a preview
}});
Another info might be that I use Realm, but my pictures are unlinked from it, so I don't think it matter
AsyncTask is asynchronous and after every completion of task, your are notifying the adapter which is causing the data change event so
#Override
protected void onPostExecute(Bitmap result) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
// FotoGridAdapter.this.notifyDataSetChanged();
// ^^^^^^^^^^^^^^^^ remove this
// not required in case of change in imageview
}
this.cancel(true);
}
I'm new in android and stuck at one step, so really need someones help.
I m code for small piece of program, that should parse Json local file, and post it to activity. Image decode with Base64 to Bitmap and given to CustomAdapter(extends Base Adapter). I check program's steps with Log.
AsyncTask make all correct, but in method "Oncreate view" it seems to run nothing.
Her is my code. I m really have no idea , what the problem, help!
My MainFragment+AsyncTask
public class MainFragment extends Fragment {
ArrayList<Bitmap> bitArray;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listview = (ListView)rootView.findViewById(R.id.listViewPost);
Log.v("Pl","1");
listview.setAdapter(new CustomListAdapter(getContext(), bitArray));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getActivity(), "YESS", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
}
private void updatePost() {
FetchPosterTask postTask = new FetchPosterTask(getActivity());
postTask.execute("uk_news.json");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updatePost();
}
class FetchPosterTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
private final String LOG_TAG = FetchPosterTask.class.getSimpleName();
private Context context;
public FetchPosterTask (Context myContext) {
this.context = myContext;
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
if(params.length ==0 ){
return null;
}
String json = null;
try {
json = getJson(params[0]);
} catch (IOException e)
{
e.printStackTrace();
}
try {
String[] masPst = getPosterfromJsonAsString(json);
ArrayList<Bitmap> result =decodeImageToBitmap(masPst);
return result;
}catch (JSONException e){
Log.e(LOG_TAG, "Place 5", e);
}
return null;
}
private String getJson(String filename) throws IOException{
InputStream is = this.context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
}
private String[] getPosterfromJsonAsString(String posterJson) throws JSONException {
final String OWM_NFO = "nfo";
final String OWM_NWS = "nws";
final String OWM_PST = "pst";
JSONObject imageJson = new JSONObject(posterJson);
JSONObject nfoArray = imageJson.getJSONObject(OWM_NFO);
JSONArray nwsArray = nfoArray.getJSONArray(OWM_NWS);
String[] resultStr = new String[nwsArray.length()];
for(int i =0; i<nwsArray.length(); i++){
JSONObject pst = nwsArray.getJSONObject(i);
String im = pst.getString(OWM_PST);
resultStr[i] = im;
}
return resultStr;
}
public ArrayList<Bitmap> decodeImageToBitmap (String[] base64Image) {
ArrayList<Bitmap> bitmapArrayList = new ArrayList<Bitmap>();
for(int i =0; i<4; i++) {
byte[] decodedString = Base64.decode(base64Image[i], Base64.DEFAULT);
Bitmap base64Bitmap = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
bitmapArrayList.add(i, base64Bitmap);
}
return bitmapArrayList;
}
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
if(bitArray == null){
bitArray = new ArrayList<>(bitmapArrayList);
}
else{
for(Bitmap bit: bitmapArrayList){
bitArray.clear();
bitArray.add(bit);
}
}
}
}
}
CustomListAdapter
public class CustomListAdapter extends BaseAdapter {
private final String LOG_TAG = CustomListAdapter.class.getSimpleName();
private ArrayList<Bitmap> bitmapArrayList;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<Bitmap> bitmapArrayList) {
this.bitmapArrayList = bitmapArrayList;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return bitmapArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_post_item, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.list_item);
convertView.setTag(holder);
Log.v(LOG_TAG,"1");
}
else {
holder = (ViewHolder) convertView.getTag();
Log.v(LOG_TAG,"2");
}
Log.v(LOG_TAG,"3");
holder.imageView.setImageBitmap((Bitmap)getItem(position));
Log.v(LOG_TAG,"4");
return convertView;
}
static class ViewHolder {
ImageView imageView;
}
}
Layouts
list_post_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_item"/>
</LinearLayout>
fragment main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="273dp"
android:layout_height="wrap_content"
android:id="#+id/listViewPost" />
</LinearLayout>
Your Adapter Has Not Any Item So Please change That on Adapter
#Override
public int getCount() {
return bitmapArrayList.size();
}
And also call updatePost() methed in onActivityCreated() Mehhed
I have a fagment with a Listview which have an ImageView and a Textview inside. So when the fragment creates, I call an AsyncTaskLoader for populating it. In the onLoadFinished method I set the adaptor for the list. The problem is that I cant access getLoadedManager :S
Here is the code:
This is the onLoadFinishedMethod from the first Task
public void onLoadFinished(Loader<ArrayList<Entrada>> loader, ArrayList<Entrada> entradas) {
//progress.setVisibility(View.GONE);
entradaAdapter adapter = new entradaAdapter(getActivity(), entradas);
ListView entradas_list = (ListView)rootView.findViewById(R.id.entries_list);
entradas_list.setAdapter(adapter);
for (Entrada e : entradas) {
e.loadImagen(adapter);
}
}
The adapter:
class entradaAdapter extends ArrayAdapter<Entrada> {
private final ArrayList<Entrada> lista;
LayoutInflater inflater;
public entradaAdapter(Context context, ArrayList<Entrada> lista) {
super(context, 0, lista);
this.lista = lista;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final Entrada e = getItem(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.entrada, null);
}
holder = new ViewHolder();
holder.nombre = (TextView) convertView.findViewById(R.id.text_entryTitle);
holder.imagen = (ImageView) convertView.findViewById(R.id.imageEntry);
holder.nombre.setText(e.getNombre());
if (e.getImage() != null) {
Drawable d = new BitmapDrawable(getContext().getResources(),e.getImage());
holder.imagen.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.imagen.setImageDrawable(d);
}
return convertView;
}
class ViewHolder {
TextView nombre;
ImageView imagen;
}
public int getCount() {
return lista.size();
}
public Entrada getItem(int arg0) {
return lista.get(arg0);
}
public long getItemId(int position) {
return position;
}
}
The 'Entrada' class
class Entrada implements android.support.v4.app.LoaderManager.LoaderCallbacks<Bitmap> {
private String imgUrl, nombre,categoria;
private Bitmap image;
private entradaAdapter adapter;
Context context;
public Entrada(Context context, String nombre, String categoria, String imgFile) {
this.context = context;
this.nombre = nombre;
this.categoria = categoria;
this.imgUrl = "http://erasmusapp.byethost13.com/images/entries/"+imgFile;
}
#Override
public Loader<Bitmap> onCreateLoader(int id, Bundle args) {
return new ImageLoadTask(context,imgUrl);
}
#Override
public void onLoadFinished(Loader<Bitmap> loader, Bitmap bitmap) {
if (bitmap != null) {
image = bitmap;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onLoaderReset(Loader<Bitmap> loader) {
}
public String getImgUrl() {
return imgUrl;
}
public String getNombre() {
return nombre;
}
public String getCategoria(){return categoria;}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public Bitmap getImage() {
return image;
}
public entradaAdapter getAdapter() {
return adapter;
}
public void setAdapter(entradaAdapter adapter) {
this.adapter = adapter;
}
public void loadImagen(entradaAdapter adapter){
this.adapter = adapter;
if (imgUrl != null && !imgUrl.equals("")) {
getLoaderManager().initLoader(0, null, this);
}
}
}
And the second task:
class ImageLoadTask extends AsyncTaskLoader<Bitmap> {
String imgUrl;
Bitmap mBitmap;
public ImageLoadTask(Context context, String imgUrl){
super(context);
this.imgUrl = imgUrl;
}
#Override
protected void onStartLoading() {
if (mBitmap != null) {
deliverResult(mBitmap);
}else {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
public Bitmap loadInBackground() {
Bitmap b = null;
try {
try {
URL url = new URL(imgUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
b = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return b;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
public void deliverResult(Bitmap bitmap) {
mBitmap = bitmap; // Caching
super.deliverResult(mBitmap);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
mBitmap = null;
}
}
Here I am getting stored picture paths from the database. So that I am showing the images in the gridview with the help of paths. But as it is shown in my code below, I am loading cursoradapter in the asynctask. The problem here is for the first time it is okay that it takes some time until all images are loaded.
But if user adds one more pic to the database, it again takes much time to load all images as I kept the asynctask in onResume() to make the added picture also visible. The same is the case whenever user adds each picture. Can someone suggest me a simple way to get the last added picture visible in the gridview without having to load all the pictures again. Or in the least case can some one help me implementing lazy adapter to the present cursoradapter if that is not possible?
public class ImagesScreen extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.images_screen);
gridView = (GridView)findViewById(R.id.gridView1);
String[] from = new String[] { Reminders.MOM_PATHS };
int[] to = new int[] {};
dbCon = new SQLiteConnectClass(ImagesScreen.this);
imageCursorAdapter = new ImageCursorAdapter(ImagesScreen.this, R.layout.griditem, null, from, to);
gridView.setAdapter(imageCursorAdapter);
}
protected void onResume() {
super.onResume();
new GetImages().execute((Object[]) null);
}
private class GetImages extends AsyncTask<Object, Object, Cursor> {
#Override
protected Cursor doInBackground(Object... params) {
return dbCon.getAllImages();
}
#Override
protected void onPostExecute(Cursor result) {
imageAdapter.changeCursor(result);
}
public void addpictures(View view){
// code for adding picture paths to the database by transferring to another activity.
}
}
CustomAdapter class:
public class ImageCursorAdapter extends SimpleCursorAdapter{
private int layout;
private LayoutInflater mLayoutInflater;
private Context mContext;
public ImageAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
mLayoutInflater=LayoutInflater.from(context);
mContext = context;
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mLayoutInflater.inflate(layout, parent, false);
return v;
}
public void bindView(final View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex("id"));
final String imagepath = c.getString(c.getColumnIndex("paths"));
ImageView imageview = (ImageView)v.findViewById(R.id.imageView1);
File imgFile = new File(imagepath);
if(imgFile.exists()){
Bitmap imageBitmap = decodeFile(imgFile);
imageview.setImageBitmap(imageBitmap);
}
}
}
use this code
public class Imagegallery extends Activity implements OnItemClickListener,
OnScrollListener, OnTouchListener {
Button btn;
SQLiteDatabase sampleDB = null;
String SAMPLE_DB_NAME = "hic";
int size = 0;
TextView headertext;
Button cartbtn;
ImageView footer1, footer2, footer3, footer4, footer5;
GridView gridView;
boolean larg = false;
String products;
int j = 1;
int ii = 0;
String imagepath[];
String productname[];
int productid[] = new int[1000];
String productids[] = new String[1000];
int integerprodids[] = new int[1000];
final Context context = this;
String filename2[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentspecial);
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "aiwhic/product" + File.separator);
File[] fileName = root.listFiles();
filename2 = new String[fileName.length];
for (int j = 0; j < fileName.length; j++) {
Uri uri = Uri.fromFile(fileName[j]);
filename2[j] = fileName[j].getAbsolutePath();
Log.e("file", filename2[j]);
}
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, filename2, filename2));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
int isf = filename2[position].lastIndexOf("/");
int laf = filename2[position].lastIndexOf(".");
String filename = filename2[position].substring(isf + 1, laf);
int pos = Integer.parseInt(filename);
Intent go = new Intent(Imagegallery.this, ItemsPage.class);
Bundle bundle = new Bundle();
bundle.putInt("position", pos);
bundle.putString("whichclass", "imagegallery");
bundle.putInt("catid", 2);
go.putExtras(bundle);
startActivity(go);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
private final String[] mobileimages;
public ImageAdapter(Context context, String[] mobileValues, String[] mo) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileimages = mo;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.currentspeciallist, null);
TextView textView = (TextView) gridView
.findViewById(R.id.textView1);
textView.setText(mobileValues[position]);
textView.setVisibility(View.INVISIBLE);
ImageView imageView = (ImageView) gridView
.findViewById(R.id.imageView1);
imageView.setTag(mobileimages[position]);
new Loadimage().execute(imageView);
// imageView.setImageBitmap(BitmapFactory
// .decodeFile(mobileimages[position]));
} else {
gridView = (View) convertView;
}
return gridView;
}
public int getCount() {
return mobileimages.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
}
class Loadimage extends AsyncTask<Object, Void, Bitmap> {
private ImageView imv;
private String path;
#Override
protected Bitmap doInBackground(Object... params) {
imv = (ImageView) params[0];
path = imv.getTag().toString();
// Bitmap thumb = BitmapFactory.decodeFile(path);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(path, opts), 120, 120, false);
return thumb;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (!imv.getTag().toString().equals(path)) {
/*
* The path is not same. This means that this image view is
* handled by some other async task. We don't do anything and
* return.
*/
return;
}
if (bitmap != null && imv != null) {
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(bitmap);
} else {
imv.setVisibility(View.GONE);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
then create a xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" >
</ImageView>
</RelativeLayout>
i am getting file path directly . u just get the name from sqlite and pass the array string
use Android-Universal-Image-Loader
and set
ImageView imageview = (ImageView)v.findViewById(R.id.imageView1);
File imgFile = new File(imagepath);
if(imgFile.exists()){
imageLoader.displayImage(imageUri(ur file path), imageView);
}
I have an application which allow to download 3 images and show them into a gallery
In order to do this , i use a thread in order to download the images and a handler in order to put the images into the gallery
The problem is that the images are not displayed(imageviews are empty) into the gallery (even if i see 3 imageview for my 3 images)
I do not know if this is because the connection is very slow (I develop on a mobile) or if it's because the ui is displayed before images are downloaded
Thank you very much for your help
public class ChoiceLanguage extends Activity {
private TextView nomLangue;
private ArrayList<Language> listeLangues;
private ArrayList<String> listImages;
private Gallery gallery;
private String URL="******************";
private Drawable mNoImage;
Bitmap bitmap;
ImageView imgView = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choice_language);
listeLangues= getIntent().getParcelableArrayListExtra("listeLangues");
listImages=buildListImages();
gallery = (Gallery) findViewById(R.id.galleryImg);
gallery.setAdapter(new AddImgAdp(this));
gallery.setSpacing(10);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.out.println("URL "+ listImages.get(position) );
}
});
}
private InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
in=conn.getInputStream();
return in;
}
private Bitmap downloadImage( ImageView iView, String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedInputStream bis ;
try {
in = openHttpConnection(url);
bis= new BufferedInputStream(in, 8192);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private ArrayList<String> buildListImages() {
ArrayList<String> listImg = new ArrayList<String>();
for(Language l : listeLangues) {
listImg.add(URL+l.getImagePath());
}
return listImg;
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return listImages.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imgView = new ImageView(cont);
} else {
imgView = (ImageView)convertView;
}
ThreadDownload progressDl= new ThreadDownload(position);
progressDl.start();
imgView.setLayoutParams(new Gallery.LayoutParams(150, 150));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
private class SetImg extends Handler {
public void handleMessage(Message msg) {
imgView.setImageBitmap(bitmap);
}
}
private class ThreadDownload extends Thread {
SetImg img= new SetImg();
int position ;
public ThreadDownload(int position)
{
super();
this.position=position;
}
public void run() {
bitmap = downloadImage(imgView,listImages.get(position));
img.sendEmptyMessage(0);
}
}
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view