How to load images effectively and efficiently on scrolling in android - android

Hello stackoverflow I'm trying to develop an application like Gallery for a particular directory of SD Card. For example I have took WhatsApp Images directory, here is my code
public class WhatsAppInboxImagesActivity extends Activity {
private ImageAdapter imageAdapter;
private ProgressDialog pd;
ArrayList<String> f = null;
File[] listFile;
Button btnDelete;
HashSet<String> selectedFile = null;
GridView imagegrid;
AlertDialog alertDialog = null;
static
{
File noFile = new File(Environment.getExternalStorageDirectory().getPath(), "/WhatsApp/Media/WhatsApp Images/Sent/.nomedia");
if(noFile.exists())
{
noFile.delete();
}
}//End of static block
private void initialize()
{
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
btnDelete = (Button) findViewById(R.id.btnDeleteImg);
selectedFile = new HashSet<String>();// list of file paths boolean checked
f = new ArrayList<String>();// list of file paths
}//End of initialize method
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whats_app_images_inbox);
this.initialize();
getFromSdcard();
imageAdapter = new ImageAdapter();
/*
* Performing time consuming actions
*/
new AsyncTask<Void, Void, Void>()
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(WhatsAppInboxImagesActivity.this,
"Loading..", "Please Wait", true, false);
}// End of onPreExecute method
#Override
protected Void doInBackground(Void... params)
{
return null;
}// End of doInBackground method
#Override
protected void onPostExecute(Void result)
{
imagegrid.setAdapter(imageAdapter);
imageAdapter.notifyDataSetChanged();
pd.dismiss();
}
}.execute((Void[]) null);
btnDelete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new AsyncTask<Void, Void, Void>()
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(WhatsAppInboxImagesActivity.this,
"Loading..", "Please Wait", true, false);
}// End of onPreExecute method
#Override
protected Void doInBackground(Void... params)
{
#SuppressWarnings("rawtypes")
Iterator iterator = selectedFile.iterator();
while (iterator.hasNext())
{
new File(iterator.next().toString()).delete();
}//End of while loop
return null;
}// End of doInBackground method
#Override
protected void onPostExecute(Void result)
{
pd.dismiss();
}//End of onPostExecute method
}.execute((Void[]) null);
finish();
startActivity(getIntent());
}//End of onClick method
});//End of btnDelete anonymous class
}//End of onCreate method
public void getFromSdcard()
{
File file = new File( Environment.getExternalStorageDirectory().getPath(), "/WhatsApp/Media/WhatsApp Images");
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
if(listFile[i].isDirectory())
{
continue;
}
f.add(listFile[i].getAbsolutePath());
}//End of for loop
}//End of if condition
}//End of getFromSdcard method
public class ImageAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
public ImageAdapter()
{
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}//End of ImageAdapter constructor
public int getCount()
{
return f.size();
}//End of getCount method
public Object getItem(int position)
{
return position;
}//End of getItem method
public long getItemId(int position)
{
return position;
}//End of getItemId method
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}//End of if condition
else
{
holder = (ViewHolder) convertView.getTag();
}//End of else
BitmapFactory.Options options = new BitmapFactory.Options();
// will results in a much smaller image than the original
options.inSampleSize = 4;
// don't ever use a path to /sdcard like this, but I'm sure you have a sane way to do that
// in this case nebulae.jpg is a 19MB 8000x3874px image
final Bitmap b = BitmapFactory.decodeFile(f.get(position), options);
holder.imageview.setImageBitmap(b);
return convertView;
}//End of getView method
}//End of ImageAdapter instance inner class
class ViewHolder
{
ImageView imageview;
CheckBox checkbox;
int id;
}//End of ViewHolder instance inner class
}//End of WhatsAppImagesActivity
So far every thing is good, but the problem is images gets loaded all at one shot, so scrolling is very slow and some times OutOfMemoryException occurs though decoded file with BitMapFactory, can any one help me to solve this puzzle please.
Edit:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.BLACK);
viewHolder.image = (ImageView) view.findViewById(R.id.image);
viewHolder.image.setVisibility(View.GONE);
viewHolder.cb = (CheckBox) view.findViewById(R.id.item_check_box);
viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar);
view.setTag(viewHolder);
} else {
view = convertView;
}
final int pos = position;
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.image.setTag(list.get(position).getURL());
holder.image.setId(position);
PbAndImage pb_and_image = new PbAndImage();
pb_and_image.setImg(holder.image);
pb_and_image.setPb(holder.pb);
new DownloadImageTask().execute(pb_and_image);
return view;
}
Thanks.

You should use Lazy loading
visit this tutorial for lazy loading here Its very easy.
Let me know if you have any issue on it.
Edit
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path = Environment.getExternalStorageDirectory()+"/WhatsApp/Media/WhatsApp Images";
final List<Model> list = new ArrayList<Model>();
final File file = new File(path);
final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "",
"Please Wait...", true);
new Thread(new Runnable() {
public void run() {
dismissDialog(dialog);
for(File fileChild : file.listFiles()){
list.add(get(fileChild.getName(), fileChild.getAbsolutePath()));
}
}
}).start();
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
setListAdapter(adapter);
}
public void dismissDialog(final ProgressDialog dialog) {
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private Model get(String s, String url) {
return new Model(s, url);
}
}

This could help: UniversalImageLoader
And that's what I did:
/**
* UniversalImageLoader載入遠端圖片,僅使用RAM做圖片快取 (Load pic & use RAM as cache)
* #param android.content.Context
* #author https://github.com/nostra13/Android-Universal-Image-Loader
* #param android.widget.ImageView - 顯示圖片的元件 (your image container)
* #param int - 載入失敗的預設圖片Resource ID (default pic if load fail, I put default pic in resources folder)
* #param java.lang.String - 檔案URL (pic URL or path)
*/
public static void imageLoaderMemoryCache(Context context, final ImageView img, final int failImgID, String url)
{
ImageLoader imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(100, 100) // max width, max height
.threadPoolSize(5)
.threadPriority(Thread.NORM_PRIORITY+1)
.denyCacheImageMultipleSizesInMemory()
.tasksProcessingOrder(QueueProcessingType.FIFO)
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.enableLogging()
.build();
imageLoader.init(config);
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.cover_sample)
.cacheInMemory(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.bitmapConfig(Bitmap.Config.RGB_565)
.delayBeforeLoading(1)
.displayer(new FadeInBitmapDisplayer(500))
.build();
imageLoader.displayImage(url, img, options, new ImageLoadingListener()
{
#Override
public void onLoadingStarted(String url, View view)
{img.setImageResource(failImgID);} //一開始先顯示預設圖 (display default pic at first)
#Override
public void onLoadingFailed(String url, View view, FailReason failReason)
{img.setImageResource(failImgID);}
#Override
public void onLoadingComplete(String url, View view, Bitmap loadedImage)
{}
#Override
public void onLoadingCancelled(String url, View view)
{}
});
}
Usage (ListView)
public View getView(...)
{
vh.imgCover=(ImageView)convertView.findViewById(R.id.imgCover);
//...
// some stuff
//...
Util.imageLoaderDiskCache(getActivity(), vh.imgCover, R.drawable.cover_sample, "(pic file path)");
}
Hope it helps~

Related

Onitem long click not working for listvview

I have a activity which implements onitemlongclicllstener to a list view. I use parse.com as my back end for retrieving data into listvview. Everything works fine but onitemlongclicllstener don't work on list view. Nothing happens when list item is long clicked
my main activity
public class InterActivity extends Activity implements OnItemLongClickListener
{
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
FinalAdapter adapter;
List<CodeList> codelist = null;
SharedPreference shrdPreference;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inter_layout);
shrdPreference = new SharedPreference();
//Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Please wait loading ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
ob = query.find();
for (ParseObject inter : ob) {
ParseFile video = (ParseFile) inter.get("demovideo");
// ParseFile downloadfile = (ParseFile) inter.get("download");
CodeList map = new CodeList();
map.setListHeading((String) inter.get("listheading"));
map.setSingleItemHeading((String) inter.get("heading"));
map.setDownloadCode((String) inter.get("download"));
map.setDailogdemovideo(video.getUrl());
// map.setDownloadCode(downloadfile.getUrl());
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.inter_layoutListView);
// Pass the results into ListViewAdapter.java
adapter = new FinalAdapter(InterActivity.this,
codelist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemLongClickListener(InterActivity.this);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3)
{
ImageView fvrtebutton = (ImageView) view.findViewById(R.id.favbtn);
String tag = fvrtebutton.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPreference.addFavorite(InterActivity.this, codelist.get(position));
Toast.makeText(InterActivity.this, getString(R.string.fav_added),
Toast.LENGTH_SHORT).show();
fvrtebutton.setTag("yes");
fvrtebutton.setImageResource(R.drawable.favorite);
} else {
shrdPreference.removeFavorite(InterActivity.this, codelist.get(position));
fvrtebutton.setTag("no");
fvrtebutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(InterActivity.this,
getString(R.string.fav_removed),
Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
final adapter.java
public class FinalAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ImageLoader imgLoader;
private List<CodeList> codeList = null;
private ArrayList<CodeList> arraylist;
SharedPreference shrdprfrnce;
public FinalAdapter(Context context,
List<CodeList> codeList) {
this.context = context;
this.codeList = codeList;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<CodeList>();
this.arraylist.addAll(codeList);
shrdprfrnce = new SharedPreference();
imageLoader = new ImageLoader(context);
}
public class ViewHolder{
TextView listHeading;
TextView listHash;
ImageView alphabetList;
ImageView favariteImage;
}
#Override
public int getCount()
{
return codeList.size();
}
#Override
public Object getItem(int position)
{
return codeList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
//holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favariteImage = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList codes = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
if (checkFavoriteItem(codes)) {
holder.favariteImage.setImageResource(R.drawable.favorite);
holder.favariteImage.setTag("yes");
} else {
holder.favariteImage.setImageResource(R.drawable.unfavorite);
holder.favariteImage.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return view;
}
public boolean checkFavoriteItem(CodeList checkCodes) {
boolean check = false;
List<CodeList> favorites = shrdprfrnce.getFavorites(context);
if (favorites != null) {
for (CodeList codes : favorites) {
if (codes.equals(checkCodes)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList codes) {
(
codeList.add(codes);
notifyDataSetChanged();
}
public void remove(CodeList codes) {
codeList.remove(codes);
notifyDataSetChanged();
}
}
plz remove
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
bcoz it Get Full view Click Thats y ur OnLongClick is not working yet
try with return true;
#Override
public boolean onItemLongClick(AdapterView < ? > arg0, View arg1,
int pos, long id) {
Log.v("long clicked", "pos: " + pos);
return true;
}

Reload ImageView by URI on ListView

I have a ListView of elements composed with ImageView. I get a new image using an AsyncTask and in the onPostExecute(Object result) method I set the image using setImageUri(Uri uri) but it doesn't gets updated.
If I change of activity or between apps, image is shown perfectly, but I want to show the image immediately.
I tried calling invalidate() with all the combinations of the ImageView, the extended BaseAdapter, the parent ListView, but nothing worked. I tried many other techniques like calling setImageResource(0), setImageUri(null), but no results...
EDITED:
Here, part of the code:
public class ThingItemAdapter extends BaseAdapter {
protected List<Thing> things;
LayoutInflater inflater;
public ThingItemAdapter(Context context, List<Thing> things) {
this.things = things;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return things.size();
}
#Override
public Thing getItem(int position) {
return things.get(position);
}
#Override
public long getItemId(int position) {
return things.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.thing_list_item, parent, false);
holder.thingImageView = (ImageView) convertView.findViewById(R.id.thing_preview);
holder.button = (ImageButton) convertView.findViewById(R.id.apply_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Thing thing = things.get(position);
final long thingId = thing.getId();
final Uri thingUri = thing.getPicture();
holder.thingImageView.setImageURI(thingUri);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// generate new file
final TypedFile typedFile = new TypedFile("multipart/form-data", new File(thingUri.getPath()));
new ReadAndStorePictureTask()
.execute(new Object[] { typedFile, holder.thingImageView, thing });
}
});
// item detailed view listener
holder.thingImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent((ThingApplication) ThingApplication.getContext(), ThingActivity.class);
intent.putExtra(ThingActivity.EXTRA_THING_ID, thingId);
context.startActivity(intent);
}
});
return convertView;
}
private class ViewHolder {
ImageView thingImageView;
ImageButton button;
}
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
Thing thing;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
thing = (Thing) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
thing.setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(thing);
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
imageView.setImageURI(thing.getPicture());
// force redraw. FIXME not working
/*
* ANSWER HERE, PLEASE
*/
}
}
}
How can I show the updated URI immediately inside onPostExecute(Object result) method?
onPostExecute you update the list of images that it's linked to the ListView adapter and after that you notify the adapter that you changed the items in the list by calling:
adapter.notifyDataSetChanged();
You can do something like this:
-Change third parameter in asynctask call.
new ReadAndStorePictureTask().execute(
new Object[] { typedFile, holder.thingImageView, pos });
-Then, modify the list items inside asynctask and refresh.
private class ReadAndStorePictureTask extends AsyncTask<Object, Void, Void> {
ImageView imageView;
int position;
ViewGroup parent;
protected Void doInBackground(Object... params) {
final TypedFile typedFile = (TypedFile) params[0];
imageView = (ImageView) params[1];
position = (Integer) params[2];
((ThingApplication) ThingApplication.getContext()).getClient().apply(typedFile,
new Callback<Response>() {
#Override
public void failure(RetrofitError error) {
...
}
#Override
public void success(Response nothing, Response response) {
try {
byte[] bytes = ThingApplication.getBytesFromStream(response.getBody().in());
Uri newImageURI = Uri.parse("uri://valid_uri"); // whatever, it exists in real code
things.get(position).setPicture(newImageURI);
File file = ((ThingApplication) ThingApplication.getContext())
.getFileFromURI(newImageURI); // this method works
ThingApplication.saveBytesToFile(bytes, file.getAbsolutePath());
thingService.storeThing(things.get(position));
} catch (Exception e) {
...
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
notifyDataSetChanged();
}
}
Good luck!

Universal Image Loader - listView was cleared

A few hours ago, I asked about AUIL call too many getView(). (Universal Image Loader - call too many getView())
By answers, I solve the problem that getView() was called too many times.
However, I've still have a problem.
When the activity was started, I can see the list. However, soon after, the list view was removed (or cleared). No images appear or load on the list view.
This is my source code.
public class MainActivity extends Activity{
AsyncTask<Void, Void, Void> asyncTask, registerTask;
DisplayImageOptions options;
ArrayList<HashMap<String, Object>> feedList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int cacheSize = ((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() * 1024 * 1024 / 8;
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(metrics.widthPixels, metrics.heightPixels)
.diskCacheExtraOptions(metrics.widthPixels, metrics.heightPixels, null)
.memoryCache(new LruMemoryCache(cacheSize))
.memoryCacheSize(cacheSize)
.memoryCacheSizePercentage(13)
.diskCache(new UnlimitedDiscCache(StorageUtils.getCacheDirectory(this)))
.diskCacheSize(100 * 1024 * 1024)
.diskCacheFileCount(200)
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
.imageDownloader(new BaseImageDownloader(this))
.imageDecoder(new BaseImageDecoder(false))
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.build();
ImageLoader.getInstance().init(config);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
asyncTask = new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
StyleFeedServerUtils serverUtils = new StyleFeedServerUtils();
feedList = serverUtils.getStyleFeedList(MainActivity.this);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(feedList != null && feedList.size() > 0){
final ListView listView = (ListView)findViewById(R.id.list);
listView.setAdapter(new ImageAdapter());
PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), true, true);
listView.setOnScrollListener(listener);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("fashion", "onItemClick, position : "+position);
}
});
}
asyncTask.cancel(!isCancelled());
asyncTask = null;
}
};
asyncTask.execute(null, null, null);
}
#Override
public void onDestroy() {
super.onDestroy();
if (registerTask != null) {
registerTask.cancel(true);
}
//GCMRegistrar.onDestroy(this);
AnimateFirstDisplayListener.displayedImages.clear();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
ImageAdapter() {
inflater = LayoutInflater.from(MainActivity.this);
}
#Override
public int getCount() {
return feedList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null){
view = inflater.inflate(R.layout.style_feed_list_view, parent, false);
view.setTag((ImageView)view.findViewById(R.id.style_feed_image));
}
ImageLoader.getInstance().displayImage(feedList.get(position).get("URL").toString(), (ImageView)view.getTag(), options, animateFirstListener);
return view;
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Please help.
some times it create problem due to RoundedBitmapDisplayer just comment .displayer(new RoundedBitmapDisplayer(20)) this line and try to run again.
If you want to use rounded image view then try library from below
https://github.com/vinc3m1/RoundedImageView

How to set Text in Textview when Click on selected item in Listview?

I am using Listview with ViewHolder, and setText in Textview then display error. How to setText in Textview in Listview? Whenever I click on Like Button then I get the total count for Like but I am not able to setText on TextView for every item. whenever click on selected item then Its TextView Increment by 1 Its Successfully. get strCount is Successfully but how to setText for Selected TextView when Click on Selected Image and My code is,
My Screenshot is which is Listview and set Multiple Items in Listview Like,
My Adapter Class,
public class Adapter1 extends BaseAdapter {
public ArrayList<HashMap<String, String>> arr = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getData = new HashMap<String, String>();
String url = null, urlCount = null;
String strId = null, strCount = null;
ViewHolder viewHolder = null;
public Adapter1(Context context, ArrayList<HashMap<String, String>> arr) {
this.context = context;
this.arr = arr;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return arr.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
/** initialize ViewHolder */
viewHolder = new ViewHolder();
/** Initialize Widgets */
/** Imageview */
viewHolder.img = (ImageView) convertView.findViewById(R.id.img);
/** TextView */
viewHolder.txtId = (TextView) convertView.findViewById(R.id.txtId);
viewHolder.txt = (TextView) convertView.findViewById(R.id.txt);
getData = arr.get(position);
viewHolder.txtId.setText(getData.get(Fragment1.TAG_ID));
viewHolder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strId = arr.get(position).get(Fragment1.TAG_ID);
System.out.println("!!!!!!!!!! strId======"+ strId);
url = "http://example.com/createpost.php?id="+ strId + "&user_id="+ myDetail.getUserId();
new sendData().execute();
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
/** ViewHolder Class */
#SuppressLint("NewApi")
public class ViewHolder {
ImageView img = null,
TextView txtId = null
txt = null;
}
public class sendData extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlLike, ServiceHandler.GET);
System.out.println("!!!!!!!!!!!!!!!jsonStr in Do in===" + jsonStr);
Log.d("Response : Like", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
urlCount = "http://example.com/getalldata.php?id="+ strId;
new getCountData().execute();
};
}
/** Count the Total Like for Selected Items. */
private class getCountData extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonobject = JSONFunctions.getJSONfromURL(urlCount);
try {
strCount = jsonobject.getString("countdata");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("!!!!!!!!strCount====" + strCount);
viewHolder.txt.setText(String.valueOf(strCount));
}
}
}
Thanks in advance.
In onClick() function you have to get instance of textview and pass it to AsyncTask
// if text and img have same parent the you can find textview like this is
TextView tv =(TextView)v.getParent().findViewById(R.id.txt);
// if not then apply call getParent() function multiple time as per your layout
new sendData(tv).execute();
//Create constructor in sendData
public class sendData extends AsyncTask {
private TextView tv;
public sendData(TextView v){
tv=v;
}
...
protected void onPostExecute(Void result) {
super.onPostExecute(result);
urlCount = "http://example.com/getalldata.php?id="
+ strId;
new getCountData(tv).execute();
};
}
private class getCountData extends AsyncTask {
private TextView v;
public sendData(TextView v){
tv=v;
}
....
// in onPostExecute use
tv.setText(String.valueOf(strCount));
}
Edit: you can get correct position by tag position to view and get it inside onClick
// add this line before return
viewHolder.img.setTag(position);
// get position inside onClick()
int position =(Integer)v.getTag();

ListView disappears after reloading it again

I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}
It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.
Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);

Categories

Resources