AsyncTask doesn`t work in custom adapter - android

I`m create list of points of sales from SQLite using custom adapter
dbHelper = new YourVoiceDatabaseHelper(getActivity());
pointsList = new ArrayList<Point>();
List<Point> pl = new ArrayList<Point>();
PointsListArrayAdapter adapter;
adapter = new PointsListArrayAdapter(getActivity().getApplicationContext(),
pointsList,
getActivity().getFilesDir(),
getResources().getString(R.string.Local_Resorces_Folder),
dbHelper);
pointsListView.setAdapter(adapter);
pl = dbHelper.getAllPoints();
if(myLocation != null) {
for (Point el : pl) {
elLocation.setLatitude(Double.parseDouble(el.getLatitude()));
elLocation.setLongitude(Double.parseDouble(el.getLongtitude()));
if (myLocation.distanceTo(elLocation) <= 999) {
pointsList.add(el);
}
}
} else {
Toast.makeText(getActivity(), "Не удалось определить ваше местоположение, проверте ваши разрешения и настройки",
Toast.LENGTH_LONG).show();
} adapter.notifyDataSetChanged();
To custom adapter I send instance of my database ad using it in there and this slows my main tread. I`m trying to use AsyncTask in adapter to get images path from database and set images but Async do absolutely NOTHING
package ua.com.it_artel.tvoy_golos.service;
public class PointsListArrayAdapter extends BaseAdapter {
Context context;
private List<Point> pointsList;
private File appFolder;
private String resoursesFolder;
private YourVoiceDatabaseHelper dbHelper;
private String imagePath;
public PointsListArrayAdapter(Context context, List<Point> pointsList, File appFolder, String resoursesFolder, YourVoiceDatabaseHelper dbHelper) {
this.context = context;
this.pointsList = pointsList;
this.appFolder = appFolder;
this.resoursesFolder = resoursesFolder;
this.dbHelper = dbHelper;
}
#Override
public int getCount() {
return pointsList.size();
}
#Override
public Object getItem(int position) {
return pointsList.get(position);
}
#Override
public long getItemId(int position) {
return pointsList.get(position).getId();
}
static class ViewHolder {
ImageView image;
TextView adress;
TextView name;
TextView distance;
Location elLocation;
Point point;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
View rowView = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_element_layout_type_1, parent, false);
viewHolder = new ViewHolder();
viewHolder.elLocation = new Location("");
viewHolder.image = (ImageView) rowView.findViewById(R.id.item_image);
viewHolder.adress = (TextView) rowView.findViewById(R.id.item_text);
viewHolder.name = (TextView) rowView.findViewById(R.id.item_name);
viewHolder.distance = (TextView) rowView.findViewById(R.id.item_distance);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.elLocation.setLatitude(Double.parseDouble(pointsList.get(position).getLatitude()));
viewHolder.elLocation.setLongitude(Double.parseDouble(pointsList.get(position).getLongtitude()));
viewHolder.point = pointsList.get(position);
new AdapterImageSetter().execute(viewHolder);
viewHolder.adress.setText(pointsList.get(position).getAddress());
viewHolder.name.setText(dbHelper.getPartnerByUID(pointsList.get(position).getPartnerUid()).getName());
viewHolder.distance.setText(String.valueOf(Math.round(MyLocationListener.myLocation.distanceTo(viewHolder.elLocation))) + " м");
return rowView;
}
private class AdapterImageSetter extends AsyncTask<ViewHolder, Void, ViewHolder> {
#Override
protected ViewHolder doInBackground(ViewHolder... params) {
ViewHolder viewHolder = params[0];
imagePath = dbHelper.getPointsPartnerImage(viewHolder.point.getPartnerUid());
if (imagePath.equals("")) {
viewHolder.image.setImageResource(R.drawable.no_image);
} else {
Drawable dr = Drawable.createFromPath(appFolder.getPath() + "/" + resoursesFolder + "/" + imagePath);
viewHolder.image.setImageDrawable(dr);
}
return viewHolder;
}
}
}
I have tried different variations in AsyncTask and Runnable but it doesn`t work, like if there are no code.. Hope u understand my English and someone give advice

you can not perform ui related operations in doInBackground method for ui related operation just use onpostexcecute method
more about asynch task http://developer.android.com/reference/android/os/AsyncTask.html
in your code you you setting imege
if (imagePath.equals("")) {
viewHolder.image.setImageResource(R.drawable.no_image);
} else {
Drawable dr = Drawable.createFromPath(appFolder.getPath() + "/" + resoursesFolder + "/" + imagePath);
viewHolder.image.setImageDrawable(dr);
}
just add this code in onPostExecute

It`s work! I also add some code in Async, all work BUT but toooo much time is necessary for images and names appeared.
private class AdapterImageSetter extends AsyncTask {
#Override
protected ViewHolder doInBackground(ViewHolder... params) {
ViewHolder viewHolder = params[0];
viewHolder.imagePath = dbHelper.getPointsPartnerImage(viewHolder.point.getPartnerUid());
viewHolder.pointName = dbHelper.getPartnerByUID(viewHolder.point.getPartnerUid()).getName();
return viewHolder;
}
#Override
protected void onPostExecute(ViewHolder viewHolder) {
if (viewHolder.imagePath.equals("")) {
viewHolder.image.setImageResource(R.drawable.no_image);
} else {
Drawable dr = Drawable.createFromPath(appFolder.getPath() + "/" + resoursesFolder + "/" + viewHolder.imagePath);
viewHolder.image.setImageDrawable(dr);
}
viewHolder.name.setText(viewHolder.pointName);
Log.i("IMAGE PATH", viewHolder.imagePath);
Log.i("PARTNER UID", viewHolder.point.getPartnerUid());
}
}
For more information: this list is on first screen when u open app.
In first activity I replace fragment and шт the fragment I'm doing all the operations. have any ideas how to speed up operations in AsyncTask?
Thank you very much for the help!

Related

OutOfMemory Exception in gridview

basically I have a gridview, in which I show my products (from 10 or 20 up to 1K+ items) each item has a couple of custom textviews, and an Imageview.
I use ViewHolder pattern and also Picasso library to load images asynchronously. I have no problem with showing items, speed or whatsoever, so I think it's safe to say that my getview function works quite nice, although I have one major problem which is with scrolling the gridview, up and down, my memory monitor only shows increase of course the increment rate depends on the item-view contents as when I commented the image loading part for example, the rate decreased.
what I guess is somehow the generated views are always staying in the memory and something prevents them from getting collected by the GC.
although sometimes, when I scroll slowly GC comes and collects and memory gets free, but scrolling fast will always result in OOM, sooner or later.
my main question is that if I have a memory leak or not?! since the gc sometimes works (slow scrlling), and sometimes lets the app crashes with OOM Exception.
and clearly I hope to find out my problem and every little bit of help would be appreciated in advance.
xml of the fragment-layout which hosts the Gridview:
<GridView
android:id="#+id/gv_Main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:animationCache="false"
android:clickable="true"
android:descendantFocusability="beforeDescendants"
android:gravity="center"
android:scrollingCache="false"
android:verticalSpacing="10dp"
/>
my adapter(this extends CursorAdapter, although I have exactly same problem whit baseadapter as well):
public class ShygunInventoryGridCursorAdapter extends CursorAdapter {
private Context mContext;
private Cursor cursor;
private int numColumns;
private int listItemId, listItemNoImageId, gridItemId;
private String[] type;
private String[] columnTitle;
private int[] viewId;
private String textTemp;
private CyberSetting cyberSetting;
private String unitDesc = "";
private boolean isMain;
private int size;
private LayoutInflater inflater;
private int thumbSize = 200;
private File pic;
private TPictureCatalog pictureCatalog;
private TProductCatalog productCatalog;
//private ViewGroup hostActivity;
//int idTemp;
private LayoutInflater cursorInflater;
public ShygunInventoryGridCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
this.mContext = context;
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
//this.cursor = c;
productCatalog=TProductCatalog.getInstance();
cyberSetting=CyberSetting.getInstance();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = cursorInflater.inflate( R.layout.listview_inventory_product_griditems, parent, false);
ViewHolder holder = new ViewHolder();
holder.tvAttachment = (ImageView) view.findViewById(R.id.iv_inventory_products_griditems_attachment);
holder.imageCount = (TextView) view.findViewById(R.id.imagecount);
holder.tvItemCode = (TextView) view.findViewById(R.id.tv_inventory_products_griditems_ItemCode);
holder.tvProductName = (TextView) view.findViewById(R.id.tv_inventory_products_griditems_Title);
holder.tvPrice = (RialTextView) view.findViewById(R.id.tv_inventory_products_griditems_Price);
holder.tvRemain = (TextView) view.findViewById( R.id.tv_inventory_products_griditems_Remain);
holder.btnMore =(com.rey.material.widget.Button) view.findViewById(R.id.btn_inventory_products_griditems_More);
holder.btnPlus = (com.rey.material.widget.Button) view.findViewById(R.id.btn_inventory_products_griditems_addOne);
view.setTag(holder);
Log.d("CurAd","newView");
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
Log.d("CurAd","bindView");
ViewHolder holder;
holder = (ViewHolder) view.getTag();
holder.itemId = cursor.getString(cursor.getColumnIndex(DatabaseColumnContent.COL_PRODUCT_ITEM_ID.toString()));
TSimpleProduct tempProduct = productCatalog.getSimpleProductById(Integer.parseInt(holder.itemId));
holder.itemGuId = cursor.getString(cursor.getColumnIndex(DatabaseColumnContent.COL_PRODUCT_GUID.toString()));
holder.tvItemCode.setText(cursor.getString(cursor.getColumnIndex(DatabaseColumnContent.COL_PRODUCT_ITEMCODE.toString())));
holder.tvProductName.setText(cursor.getString(cursor.getColumnIndex(DatabaseColumnContent.COL_PRODUCT_ITEMDESC.toString())));
//Remain
if (cyberSetting.getSettingValue(TCyberSettingKey.SHOWITEMREMAIN).equals("1")) {
textTemp = (mContext.getString(R.string.restrictedInfo));
} else {
if (tempProduct.getDefaultUnitValue() == 2 && tempProduct.isUnitDependent()) {
String titleRemain2 = DatabaseColumnContent.COL_PRODUCT_CURSOR_REMAIN2.toString();
textTemp = cursor.getString(cursor.getColumnIndex(titleRemain2));
}
if (cyberSetting.getSettingValue(TCyberSettingKey.SHOWITEMREMAIN).equals("2")) {
if (textTemp == null) {
textTemp = "0";
}
int t = Integer.parseInt(textTemp);
if (t > 0) {
textTemp = mContext.getString(R.string.productAvailable);
} else {
textTemp = mContext.getString(R.string.productUnAvailable);
}
}
}
holder.tvRemain.setText(textTemp);
//Price
String priceLevel = "0";
try {
Register register = Register.getInstance();
priceLevel = register.getPriceLevel();
} catch (NoDaoSetException e) {
e.printStackTrace();
}
if(!priceLevel.equals("0"))
textTemp = cursor.getString(cursor.getColumnIndex(priceLevel));
else
textTemp = "0.0";
if (tempProduct.getDefaultUnitValue() == 2 && tempProduct.isUnitDependent()) {
double price2;
price2 = TLineItem.convertPrice1ToPrice2(Double.parseDouble(textTemp), tempProduct.isUnit1Bigger(), tempProduct.getUnitCoef());
textTemp = TGeneralTools.ConvertDoubleToEnglishString(price2);
if (tempProduct.getUnitDesc2() != null && !tempProduct.getUnitDesc2().equals(""))
unitDesc = " (" + tempProduct.getCompleteUnitDesc2() + ")";
} else {
if (tempProduct.getUnitDesc1() != null && !tempProduct.getUnitDesc1().equals(""))
unitDesc = " (" + tempProduct.getCompleteUnitDesc1() + ")";
}
holder.priceDef = textTemp;
holder.tvPrice.setText(textTemp + unitDesc);
holder.tvRemain.setText(holder.tvRemain.getText() + unitDesc);
//image
pictureCatalog = TPictureCatalog.getInstance();
String defGuid = "";
if (tempProduct.getHasAttachContent() >= 1 && pictureCatalog.isDownloadedAlbumAvailable()) {
defGuid = pictureCatalog.getDefaultPictureGuid(holder.itemGuId);
if (tempProduct.getHasAttachContent() == 1) {
holder.imageCount.setVisibility(View.GONE);
} else {
holder.imageCount.setVisibility(View.VISIBLE);
holder.imageCount.setText(String.valueOf(tempProduct.getHasAttachContent()));
}
} else {
holder.imageCount.setVisibility(View.GONE);
}
String filename = Environment.getExternalStorageDirectory().getPath()
+ FileAddressContent.APPLICATION_HOME_DIRECTORY
+ FileAddressContent.PICTURES_ROOT_DIRECTORY
//+ FileAddressContent.PICTURES_THUMBS_DIRECTORY.toString()
+ defGuid + FileAddressContent.PICTURES_EXTENSION;
pic = new File(filename);
if (pic.exists())
Picasso.with(mContext)
.load(pic)
.error(R.drawable.noimage)
//.placeholder(R.drawable.loading)
.resize(thumbSize, thumbSize)
.centerInside()
.into(holder.tvAttachment);
else
Picasso.with(mContext)
.load(R.drawable.noimage)
.resize(thumbSize, thumbSize)
.centerInside()
.into(holder.tvAttachment);
holder.tvAttachment.setMinimumHeight(thumbSize);
setupGridView(view, holder);
}
private void setupGridView(View view, final ViewHolder holder) {
/*final ImageView iv = (ImageView) view.findViewById(R.id.iv_inventory_products_griditems_attachment);
com.rey.material.widget.Button btMore = (com.rey.material.widget.Button) view.findViewById(R.id.btn_inventory_products_griditems_More);
com.rey.material.widget.Button btPlus = (com.rey.material.widget.Button) view.findViewById(R.id.btn_inventory_products_griditems_addOne);
//final TextView tvTitle = (TextView) view.findViewById(R.id.tv_inventory_products_griditems_Title);
final RialTextView tvPrice = (RialTextView) view.findViewById(R.id.tv_inventory_products_griditems_Price);
final TextView tvItemId = (TextView) view.findViewById(R.id.tv_inventory_products_griditems_ItemId);
final TextView tvGuId = (TextView) view.findViewById(R.id.tv_inventory_products_griditems_GuId);
//final TextView tvRemain = (TextView) view.findViewById(R.id.tv_inventory_products_griditems_Remain);*/
holder.tvAttachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* BitmapDrawable bitmapDrawable = ((BitmapDrawable) iv.getDrawable());*/
showImageDialog(holder.itemGuId);
}
});
holder.btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*addToInvoiceDialog(tvTitle.getText().toString(), tvPrice.getText().toString(), tvItemId.getText().toString(),
tvRemain.getText().toString(),iv.getDrawable(),tvGuId.getText().toString());*/
showAddToInvoiceFragment(holder.itemId, holder.priceDef);
}
});
holder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//InventoryFragment.AddToInvoice(holder.itemId, 1, holder.priceDef, null, null);
}
});
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
private void showImageDialog(String ReferenceGuId) {
//InventoryFragment.openAlbum(ReferenceGuId);
}
private void showAddToInvoiceFragment(String itemId, String priceDef) {
//InventoryFragment.showAddToInvoiceFragment(itemId, priceDef);
}
}
this is the part in my java code where I set the adapter:
ShygunInventoryGridCursorAdapter listAdapter1 = new ShygunInventoryGridCursorAdapter(context,cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
gridView.setNumColumns(colCount);
gridView.setAdapter(listAdapter1);
MAT screen( I could not reach anywhere here, I mean non of roots or ... was my own code)
Not to mention, adding System.gc() at the end of get View method in the adapter will solve everything, but I'm sure it's not the right thing to do

Show Image in listview, if file specific file is downloaded internal storage

I am working on a project. In my project when user clicks on a list item, it downloads a file from some source and saves it into internal storage.
I want to show an image in list items of listview if file is already download.
The code below is working fine but it is also showing image for the list items whose file is yet not downloaded.
Here is my adapter class code.
package life.quran.com.quranlife;
public class SurahBaseSearchAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflator;
private List<Surah> surahList = null;
private ArrayList<Surah> arrayList;
Surah surah;
ArrayList<String> imgfileLocation = null;
String searchhighlightString = "";
public SurahBaseSearchAdapter(Context context, List<Surah> list) {
mContext = context;
surahList = list;
mInflator = LayoutInflater.from(context);
arrayList = new ArrayList<Surah>();
arrayList.addAll(surahList);
}
public class ViewHolder {
TextView sname;
TextView sno;
ImageView dlimg;
}
#Override
public int getCount() {
return surahList.size();
}
#Override
public Object getItem(int position) {
return surahList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imgfileLocation = new ArrayList<>();
surah = surahList.get(position);
File f = mContext.getFilesDir();
String filepath = f.getAbsolutePath();
File _file = new File(filepath+"/surah_"+surah.getSurah_id()+".json");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflator.inflate(R.layout.item_template,null);
holder.sname = (TextView) convertView.findViewById(R.id.txt_surahName);
holder.sno = (TextView) convertView.findViewById(R.id.txtsuraNo);
holder.dlimg = convertView.findViewById(R.id.dlimg);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.sname.setText(surah.getSurah_name());
holder.sno.setText(surah.getSurah_no());
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
}
String hSurahName = surah.getSurah_name().toLowerCase(Locale.getDefault());
if(hSurahName.contains(searchhighlightString)) {
int startpos = hSurahName.indexOf(searchhighlightString);
int endpos = startpos + searchhighlightString.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.sname.getText());
spanText.setSpan(new ForegroundColorSpan(Color.BLUE),startpos,endpos,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.sname.setText(spanText,TextView.BufferType.SPANNABLE);
}
return convertView;
}
public void filter(String charText) {
searchhighlightString = charText;
charText = charText.toLowerCase(Locale.getDefault());
surahList.clear();
if(charText.length() == 0) {
surahList.addAll(arrayList);
} else {
for(Surah surah : arrayList) {
if(surah.getSurah_name().toLowerCase(Locale.getDefault()).contains(charText)) {
surahList.add(surah);
}
}
}
notifyDataSetChanged();
}
}
Let me know if anything is unclear
You require to set default drawable if file not exist condition. Add else part to this if condition like
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
}else{
holder.dlimg.setImageResource(R.drawable.<default_image>);
}
You should clear image in ViewHolder after previous usage. Just change your code to something like this:
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
} else {
//clear image from previous usage
//do not sure is it legal to set null. You need to check it.
holder.dlimg.setImageResource(null)
}

How to fetch the image using JSON in ListFragment?

I am new to android development,I am parsing my data using JSON Parsing method,I extend my class with List Fragment and I want my data in list view but the problem is i am getting all the data perfectly except the images,i don't know how to solve it,my response looks like this
{"matching":[{"name":"Monic Dano","profile_id":"GM335695","image":"http://mywebsitename.com/images/Girlnoimage.jpg","cast":"","age":"24","location":"Ivory Coast"}]}
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://mywebsitename.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age+" years");
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
// updating listview
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
}
Try to AndroidQuery with custom adapter :
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propic);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtproname);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproid);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecast);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileage);
holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplace);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
How to set adapter to ListView :
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
You can use universal image loader for viewing images from your server.Z
Just pass the image url and your view and you are good to go.
For your reference here is the link to Universal Image loader with all its documentation.
https://github.com/nostra13/Android-Universal-Image-Loader
Hop it helps you.
I am hardly suggest you to use Android Query for this. Its mind blowing api given by Android itself. You can download image, download bitmap or whatever you wanna do you can.
You can download the jar file from here :here Download the jar file and set jar to your Build Path.
AQuery androidAQuery=new AQuery(this);
As an example to load image directly from url:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
As an example to get Bitmap from url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
//Declare adapter globally.
private EfficientAdapter adapter;
//Initialize it in onCreate() method
adapter = new EfficientAdapter(this);
//Set your adapter like
listview.setAdapter(adapter);
//Adapter class code
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return aList.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.YOUR ITEM LAYOUT, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
holder.txtProfile = (TextView) convertView.findViewById(R.id.txtProfile);
holder.txtCast = (TextView) convertView.findViewById(R.id.txtCast);
holder.txtAge = (ImageView) convertView.findViewById(R.id.txtAge);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(aList.get(position).get(TAG_NAME));
holder.txtProfile.setText(aList.get(position).get(TAG_PROFILE));
holder.txtCast.setText(aList.get(position).get(TAG_CAST));
holder.txtAge.setText(aList.get(position).get(TAG_AGE));
aQuery.id(holder.imgUser).image(data.get(position).get(TAG_IMAGE), true, true);
return convertView;
}
class ViewHolder {
TextView txtName;
TextView txtProfile;
TextView txtCast;
TextView txtAge;
ImageView imgUser;
}
}
In source code of SimpleAdapter:
private void bindView(int position, View view) {
final Map dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = mViewBinder;
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this SimpleAdapter");
}
}
}
}
}
You can see if your view is ImageView , the code will use the url String be the resId in
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {#link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* #param v ImageView to receive an image
* #param value the value retrieved from the data set
*
* #see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
And your error is here , so you need Override the getView function of SimpleAdapter.Here is code:
Uri uri = Uri.parse("http://gujjumatch.com/images/Girlnoimage.jpg");
image.setImageURI(uri);
You need to create adapter and extend it to BaseAdapter and add all your items and call it in your AsyncTask's method and it will return your output as said by Haresh Chellana.

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);

How to handle ImageView inside a ListView?

I have a ListView inside an Activity and each of its item is customized to have some TextViews along with a DropDownList item and an ImageView. Inside an OnScrollListener() implementation each item of a listView gets populated using an ArrayAdapter populating text views with values taken from an arrayList and ImageView with the .jpeg file stored on SD card. Following is the screenSHot of listView Item
The problem arises when the .jpeg file from sdCard is converted to a bitmap (i.e. BitmapFactory.decodeFile(fileName) ) and then gets assigned to an image View using setImageBitmap(Bitmap bmp). As the setting bitmap image to an image view is a lengthy process it cannot keep pace with the scroll listener implementation and the ImageView of different ListView rows gets populated with the image it was assigned to any row above. Can anybody please suggest some workout to cater this issue specifically the assignment of images from SD Card to an imageView. Its not like my listView item is overLoaded with controls that is why i am facing this problem. I also have tried it with single ImageView item inside each row and it behaves the same way. Your suggestion to improvise this are welcome and surely will be of great help. Thank you :-)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
AssetDetailHolder assetDetailholder = null;
try {
if (row == null) {
LayoutInflater inflator = ((Activity) context)
.getLayoutInflater();
row = inflator.inflate(layoutResourceID, parent, false);
assetDetailholder = new AssetDetailHolder();
assetDetailholder.itemPosition = position;
assetDetailholder.txtVwlineCOde = (TextView) row
.findViewById(R.id.lineCodeValue_ad);
assetDetailholder.txtvwLocation = (TextView) row
.findViewById(R.id.locationValue_ad);
assetDetailholder.txtvwLocationDetail = (TextView) row
.findViewById(R.id.detailLocationValue_ad);
assetDetailholder.txtvwInventoryNo = (TextView) row
.findViewById(R.id.InventoryNoValue_ad);
assetDetailholder.spnrconditionCode = (Spinner) row
.findViewById(R.id.spinner_ad);
assetDetailholder.txtvwAssetName = (TextView) row
.findViewById(R.id.AssetNameValue_ad);
assetDetailholder.subNoThumbnail = (ImageView) row
.findViewById(R.id.IV_subNoThumbnail);
row.setTag(assetDetailholder);
} else {
assetDetailholder = (AssetDetailHolder) row.getTag();
assetDetailholder.itemPosition = position;
}
AssetDetail assetDetail = assetsDetailList[position];
new ThumbnailTask(position, assetDetailholder, assetDetail, context)
.execute();
if (assetDetail.assetLineCodeDesc.equals("")) {
assetDetailholder.txtVwlineCOde
.setText(assetDetail.strLineCOde);
} else {
assetDetailholder.txtVwlineCOde.setText(assetDetail.strLineCOde
+ "(" + assetDetail.assetLineCodeDesc + ")");
}
if (assetDetail.assetLocationNameDesc.equals("")) {
assetDetailholder.txtvwLocation
.setText(assetDetail.strLocationName);
} else {
assetDetailholder.txtvwLocation
.setText(assetDetail.strLocationName + "("
+ assetDetail.assetLocationNameDesc + ")");
}
assetDetailholder.txtvwLocationDetail
.setText(assetDetail.strLocationDetail);
if (assetDetail.strInventoryNumber.contains("-")) {
assetDetailholder.txtvwInventoryNo
.setText(assetDetail.strInventoryNumber.split("-")[0]);
} else {
assetDetailholder.txtvwInventoryNo
.setText(assetDetail.strInventoryNumber);
}
assetDetailholder.txtvwAssetName.setText(assetDetail.assetName);
String conditionCodeString = assetDetail.assetConditionCode;
if (conditionCodeString != "" || conditionCodeString != null) {
try {
int conditionCodeInteger = Integer
.parseInt(conditionCodeString);
assetDetailholder.spnrconditionCode
.setSelection(conditionCodeInteger);
} catch (Exception e) {
assetDetailholder.spnrconditionCode.setSelection(0);
}
} else {
assetDetailholder.spnrconditionCode.setSelection(0);
}
// String thumbnailDir = Common
// .getSubNoDirectory(context, assetDetail);
// if (new File(thumbnailDir).isDirectory()) {
//
// File thumbnailFile = new File(Common.getSubNoImgFilePath(
// thumbnailDir, assetDetail, SubNo_ImageSample.A));
//
// if (thumbnailFile.exists()) {
// assetDetailholder.subNoThumbnail
// .setImageBitmap(BitmapFactory
// .decodeFile(thumbnailFile.getAbsolutePath()));
// }
// }
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
static class AssetDetailHolder {
TextView txtVwlineCOde;
TextView txtvwLocation;
TextView txtvwLocationDetail;
TextView txtvwInventoryNo;
TextView txtvwAssetName;
Spinner spnrconditionCode;
ImageView subNoThumbnail;
public int itemPosition;
}
private static class ThumbnailTask extends AsyncTask<Void, Void, Void> {
private int mPosition;
private AssetDetailHolder mHolder;
private Context cntxt;
private AssetDetail assetItem;
private Bitmap thumbnailBmp;
public ThumbnailTask(int position, AssetDetailHolder holder,
AssetDetail asset, Context context) {
mPosition = position;
mHolder = holder;
assetItem = asset;
cntxt = context;
}
#Override
protected Void doInBackground(Void... params) {
String thumbnailDir = Common.getSubNoDirectory(cntxt, assetItem);
if (new File(thumbnailDir).isDirectory()) {
File thumbnailFile = new File(Common.getSubNoImgFilePath(
thumbnailDir, assetItem, SubNo_ImageSample.A));
if (thumbnailFile.exists()) {
thumbnailBmp = BitmapFactory.decodeFile(thumbnailFile
.getAbsolutePath());
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mHolder.itemPosition == mPosition && thumbnailBmp != null) {
mHolder.subNoThumbnail.setImageBitmap(thumbnailBmp);
}
// super.onPostExecute(result);
}
}
http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
This will be hopefull to you :P

Categories

Resources