Wrong Loading Data when using Viewholder in BaseAdapter Android - android

I am using BaseAdapter for loading the data in gridview. When the data is loaded to the gridview, and the user tries to scroll, I used to get incorrect data. In order to fix that I used ViewHolder. That actually fixed the issue, however, when the users click any of the data in the gridview, instead of getting the correct id from the item, all the items are returning a similar id number.
public class ProductAdapter extends BaseAdapter {
// Context context;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
ViewHolder holder;
int layoutResourceId;
Event event;
EventDBAdapter eventDb;
int id;
PersianCalendar sc;
String Today;
SharedPreferences Prefrences_test;
String date, userid;
String newText = "";
String test;
int status;
MoodsDBAdapter moodsDBAdapter;
Mood mood;
ArrayList<MoodsNote> arrayMoodsNote;
MoodsNoteDBAdapter moodsNoteDBAdapter;
MoodsNote moodsNote;
public ProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
// this.context = context;
eventDb = new EventDBAdapter(activity);
event = new Event();
moodsDBAdapter = new MoodsDBAdapter(activity);
mood = new Mood();
moodsNoteDBAdapter = new MoodsNoteDBAdapter(activity);
data = d;
// this.layoutResourceId = layoutResourceId;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Prefrences_test = activity.getSharedPreferences("temp", 0);
date = Prefrences_test.getString("date", "");
userid = Prefrences_test.getString("userid", "");
sc = new PersianCalendar();
Today = date;
eventDb = new EventDBAdapter(activity.getApplicationContext());
event = eventDb.getName(Today);
try {
arrayMoodsNote = moodsNoteDBAdapter.getItems(event.getID());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
holder = null;
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
if (vi == null) {
vi = inflater.inflate(R.layout.note_mood_list_item, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.mood_text);
holder.txt_id = (TextView) vi.findViewById(R.id.txt_id_mood);
holder.thumb_image = (ImageView) vi.findViewById(R.id.mood_img);
holder.linear = (LinearLayout) vi.findViewById(R.id.mood_layout);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.linear.setBackgroundResource(R.drawable.bg_mood);
//holder.txt_id.setText("");
String titles = song.get("name");
holder.title.setText(titles);
Resources res = activity.getResources();
int resourceId = res.getIdentifier(song.get("icon"), "drawable",
activity.getPackageName());
holder.thumb_image.setBackgroundResource(resourceId);
holder.txt_id.setText(song.get("id"));
try {
for (MoodsNote m : arrayMoodsNote) {
int moodd = m.getMOOD();
if (Integer.parseInt(holder.txt_id.getText().toString()) == moodd)
{
holder.linear.setBackgroundResource(R.drawable.bg_mood_on);
}
}
} catch (Exception e) {
// TODO: handle exception
}
holder.thumb_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(activity, holder.txt_id.getText().toString(), 0).show();
status = 1;
event = new Event();
int tedad = eventDb.getDate(date);
if (tedad <= 0) {
event = new Event(userid, date);
eventDb.insert(event);
}
event = eventDb.getName(date);
moodsNote = new MoodsNote();
id = 0;
id = Integer.parseInt(holder.txt_id.getText().toString());
// id = rowItem.getID();
int tedadd = moodsNoteDBAdapter.getLastItemID(id);
if (tedadd <= 0)
{
moodsNote.setMOOD(id);
moodsNote.setEVENT(event.getID());
moodsNoteDBAdapter.insert(moodsNote);
holder.linear.setBackgroundResource(R.drawable.bg_mood_on);
}
else {
moodsNoteDBAdapter.deleteId(id);
holder.linear.setBackgroundResource(R.drawable.bg_mood);
}
}
});
return vi;
}
static class ViewHolder {
ImageView thumb_image;
TextView txt_id, title;
LinearLayout linear;
}

Related

'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference

I just created an application on android optimized for the mobile phone. Now as the client asked to optimize for 17inch screen size without building separate apk. I almost implemented with some minor UI changes. But in case of listviews, they need Gridviews. So What I did was I created a separate layout for bigger screen with gridview I used a code to detect the screen size and in activity I used a code to detect the screen size and if it's bigger, then I initialized Gridview and after async task i added to a cardview adapter and set the gridview adapter to cardview adapter.
I switched gridview and listview as:
if(Constants.isScreenLarge(getActivity())) {
// width > height, better to use Landscape
mygrid = (GridView) getView().findViewById(R.id.card_gridview);
} else {
listView = (ListView)getView().findViewById(R.id.card_listView);
listView.addHeaderView(new View(getActivity()));
listView.addFooterView(new View(getActivity()));
}
Using Restclient helper:
public void fetchTransaction(){
loading.setVisibility(View.VISIBLE);
pd.setMessage("Fetching Transactions..Please Wait");
pd.setCancelable(false);
pd.show();
String fromDate = from.getText().toString();
String toDate = to.getText().toString();
//mydb.deleteAllTransactions();
cardArrayAdapter = new CardArrayAdapter(this.getActivity().getApplicationContext(), R.layout.list_item_card);
cardArrayAdapter.clear();
String android_id = Settings.Secure.getString(getActivity().getContentResolver(),
Settings.Secure.ANDROID_ID);
String userid = prefs.getString("userId","0");
Log.e("TRANSACTON", Constants.BASE_URL_TRANSACTIONS+"?deviceid="+android_id+"&userid="+userid+"&from="+fromDate+"&to="+toDate);
RestClientHelper.getInstance().get(Constants.BASE_URL_TRANSACTIONS+"?deviceid="+android_id+"&userid="+userid+"&from="+fromDate+"&to="+toDate, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
pd.dismiss();
try{
mydb.deleteAllTransactions();
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("result");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String heading = post.optString("heading");
String description = post.optString("description");
String amount = post.optString("amount");
String imageurl = post.optString("imageurl");
String credit = post.optString("credit");
String date = post.optString("date");
String type = post.optString("type");
String service = post.optString("service");
String cost = post.optString("cost");
String balance = post.optString("balance");
String amountinfo = post.optString("amountinfo");
Log.e("ENTERING TO DB","DATA"+i);
Card card = new Card(heading, description,amount,date,credit,imageurl,cost,balance,amountinfo,id,service);
cardArrayAdapter.add(card);
//mydb.addTransactionContact(new TransactionData(heading, description, amount, imageurl,credit,type,date));
}
} catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e){
}
finally {
//showTransaction();
rl = (RelativeLayout)getView().findViewById(R.id.noItems);
rl.setVisibility(view.INVISIBLE);
if(Constants.isScreenLarge(getActivity())) {
// width > height, better to use Landscape
mygrid.setAdapter(cardArrayAdapter);
} else {
listView.setAdapter(cardArrayAdapter);
}
cardArrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onError(String error) {
pd.dismiss();
SnackbarManager.show(Snackbar.with(getActivity()) // context
.text("An Error occured.. Try after sometime"));
textView2.setText("Some Error Ocurred");
rl = (RelativeLayout)getView().findViewById(R.id.noItems);
rl.setVisibility(view.VISIBLE);
loading.setVisibility(View.INVISIBLE);
}
});
}
My CardArrayAdapter code is:
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
private Context mContext;
DatabaseUserTable mydb;
PreferenceHelper prefs;
ProgressDialog pd;
static class CardViewHolder {
TextView line1;
TextView line2;
ImageView cimageView;
TextView amount;
TextView credit;
TextView date;
TextView cost;
TextView balance;
TextView amountinfo;
TextView costinfo;
TextView balanceinfo;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
mydb = new DatabaseUserTable(this.mContext);
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.line1);
viewHolder.line2 = (TextView) row.findViewById(R.id.line2);
viewHolder.amount = (TextView) row.findViewById(R.id.amount);
viewHolder.date = (TextView) row.findViewById(R.id.date);
viewHolder.credit = (TextView) row.findViewById(R.id.credit);
viewHolder.cimageView = (ImageView) row.findViewById(R.id.imageId);
viewHolder.cost = (TextView) row.findViewById(R.id.cost);
viewHolder.balance = (TextView) row.findViewById(R.id.balance);
viewHolder.amountinfo = (TextView) row.findViewById(R.id.amountinfo);
viewHolder.costinfo = (TextView) row.findViewById(R.id.costinfo);
viewHolder.balanceinfo = (TextView) row.findViewById(R.id.balanceinfo);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getLine1());
viewHolder.line1.setTextColor(Color.parseColor("#000000"));
viewHolder.line2.setText(card.getLine2());
viewHolder.line2.setTextColor(Color.parseColor("#999999"));
viewHolder.amount.setText(card.getAmount());
viewHolder.amount.setTextColor(Color.parseColor("#000000"));
viewHolder.date.setText(card.getDate());
viewHolder.date.setTextColor(Color.parseColor("#999999"));
viewHolder.credit.setText(card.getCredit());
viewHolder.credit.setTextColor(Color.parseColor("#000000"));
viewHolder.cost.setText(card.getCost());
viewHolder.cost.setTextColor(Color.parseColor("#000000"));
viewHolder.balance.setText(card.getBalance());
viewHolder.balance.setTextColor(Color.parseColor("#000000"));
viewHolder.amountinfo.setText(card.getAmountinfo());
viewHolder.amountinfo.setTextColor(Color.parseColor("#000000"));
viewHolder.costinfo.setText("Cost");
viewHolder.costinfo.setTextColor(Color.parseColor("#000000"));
viewHolder.balanceinfo.setText("Balance");
viewHolder.balanceinfo.setTextColor(Color.parseColor("#000000"));
final String salesid = card.getSalesid();
final String servicename = card.getServiceName();
row.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e("TRANSACTIONS SERVICENAM",servicename);
if(servicename.equals("VOUCHER")) {
alertBox(v,salesid);
}
else if(servicename.equals("WALLET")) {
SnackbarManager.show(Snackbar.with(v.getRootView().getContext()) // context
.text("No Reprinting available for this transaction"));
}
else if(servicename.equals("ELECTRICITY")) {
errorAlert(v,"Printing not yet supported");
//alertBoxElectricity(v,salesid);
}
else if(servicename.equals("MONEY TRANSFER")) {
//errorAlert(v,"Printing not yet supported");
alertBoxMoney(v,salesid);
}
else{
alertBoxOther(v,salesid);
}
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Log.e("card.getLine1()",card.getLine1());
Log.e("TRASACTION URL",Constants.BASE_URL_IMAGE+card.getUrl());
Picasso.with(mContext).load(Constants.BASE_URL_IMAGE+card.getUrl()).fit().placeholder(R.drawable.mobeeloadicon).error(R.drawable.mobeeloadicon).into(viewHolder.cimageView);
return row;
}
But I got the error as:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a
null object reference
How can I change CardArrayAdapter as GridViewAdapter preserving all the Card data. Any Help please
UPDATE
I got this right. It was a silly mistake. I was populating the wrong layout.

How to get listview items both visible and invisible child values

This loop return only visible position values.However I need the values of child items that are invisible.
for (int i = 0; i < material_issue_list.getCount(); i++) {
View layout = materialIssueAdapter.getViewByPositio(i, material_issue_list);
LinearLayout listItem = (LinearLayout) materialIssueAdapter.getViewByPositio(i, material_issue_list);
String batchSTR = ((AutoCompleteTextView) listItem.findViewById(R.id.batch_AutoComplete)).getText().toString();
String qtySTR = ((EditText) listItem.findViewById(R.id.issue_qty_ETD)).getText().toString();}
My full adapter class,Some one help me suggest to get the correct output.My problem I'm getting null values from the views that are invisible.
Only the visible values are being updated to arraylist.
Thanks in advance.
public class IssueMaterialAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList Dummylist;
private static LayoutInflater inflater = null;
public Resources res;
public static ArrayList<BatchNav> batchNavs_Arr;
static ArrayList<String> batch_Arr;
public static ArrayList<String> batch_data;
public static ArrayList<String> issue_qty;
LinkedHashSet<String> hashSet;
public static ArrayList<BatchModel> batchModels = new ArrayList<BatchModel>();
public static HashMap<ViewHolder, String> batch_map;
public static HashMap<ViewHolder, String> qty_map;
HashMap<String, String> mValues = new HashMap<String, String>();
ArrayList<SaveDataModel> saveDataModels;
public IssueMaterialAdapter(Activity a, ArrayList dummy) {
activity = a;
Dummylist = dummy;
loadBatch();
this.batch_map = new HashMap<>();
inflater = (LayoutInflater) activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (Dummylist.size() <= 0)
return 1;
return Dummylist.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#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 vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.material_issue_details_list, null);
holder = new ViewHolder();
holder.batch = (AutoCompleteTextView) vi.findViewById(R.id.batch_AutoComplete);
holder.issue = (EditText) vi.findViewById(R.id.issue_qty_ET);
holder.material_descrption = (TextView) vi.findViewById(R.id.material_desc);
holder.unit_issue = (EditText) vi.findViewById(R.id.unit_issue_ET);
holder.matnr = (TextView) vi.findViewById(R.id.matnr);
holder.prdgrp = (TextView) vi.findViewById(R.id.prod_grp);
vi.setTag(holder);
batch_map.put(holder, "");
FilterWithSpaceAdapter<String> farmer_co_no_adapter = new FilterWithSpaceAdapter<String>(activity,
R.layout.custom_items, batch_Arr);
holder.batch.setAdapter(farmer_co_no_adapter);
holder.batch.setThreshold(1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Dummylist.size() == AgriDistributionActivity.get_materials.size()) {
holder.material_descrption.setText(AgriDistributionActivity.get_materials.get(position));
holder.matnr.setText(AgriDistributionActivity.get_matnr.get(position));
holder.prdgrp.setText(AgriDistributionActivity.selected_prdgrp.get(position));
}
try {
if (saveDataArr.size() > 0) {
holder.batch.setText(saveDataArr.get(position).getBatch());
holder.issue.setText(saveDataArr.get(position).getQty());
holder.unit_issue.setText(saveDataArr.get(position).getQty_uom());
}
} catch (Exception e) {
}
return vi;
}
public static class ViewHolder {
public EditText issue, unit_issue;
public AutoCompleteTextView batch;
public TextView material_descrption, matnr,prdgrp;
}
private void loadBatch() {
batch_Arr = new ArrayList<String>();
batchNavs_Arr = new ArrayList<BatchNav>();
hashSet = new LinkedHashSet<>();
BatchNavEntityCollection batchNavEntityCollection = BatchNavEntityCollection.getInstance();
batchNavs_Arr = batchNavEntityCollection.getBatchOutVal();
for (int i = 0; i < batchNavs_Arr.size(); i++) {
String batch = batchNavs_Arr.get(i).getCharg();
batch_Arr.add(batch);
hashSet.addAll(batch_Arr);
batch_Arr.clear();
batch_Arr.addAll(hashSet);
}
}
public View getViewByPositio(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition) {
return listView.getAdapter().getView(position, null, listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
}
You have saveDataArr list which holds all your data.
You can add a getter if you want to do it from an activity , add something like this to your adapter :
private SaveDataModelsendLog(int position) {
return saveDataArr(position);
}
That should do the trick , having said all that you should also look at the difference between static and non-static variables ,
it seems like you have to many of them ,
Enjoy.

Positions of view in a custom ListView is repeating

I used CustomListAdapter class which extends baseadapter. In that i have a button on each view of the list view ..when I lick on the button it should print a text. everything is working fine except that the text is printed in someother view too. I have found many similar question but no exact solution.
public class CustomListAdapter extends BaseAdapter {
List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2;
ArrayList<String> listItems;
public int count1 = 0;
ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email;
int i ;
ImageButton like;
ImageButton share;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_propertiesdel = IP+"/studio/getdelete_all_agent.php";
boolean isSelected;
int a,a1,b,b1;
//private static final String TAG_SUCCESS1 = "mass";
private static final String TAG_USER = "users";
private static final String TAG_PRO = "properties";
//private static final String TAG_PRO1 = "properties1";
// products JSONArray
JSONArray users = null;
//JSONArray users1 = null;
View view;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
// int position;
public CustomListAdapter(Context context, List<HashMap<String, Object>> models) {
this.context = context;
this. models = models;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt;
public ImageButton like,share;
}
public void clear(){
if(models!=null)
models.clear();
}
#Override
public int getCount() {
return models.size();
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView( int position, final View convertView, ViewGroup parent) {
// view = null;
view = convertView;
ViewHolder viewHolder;
pos = getItemViewType(position);
// long posn = getItemId(position);
// final int paps= (int)posn ;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fragment_home2, parent, false);
//your code
//add below code after (end of) your code
viewHolder.like=(ImageButton)view.findViewById(R.id.likem);
viewHolder.share=(ImageButton)view.findViewById(R.id.share);
viewHolder.like.setTag(position);
// viewHolder.share.setTag(position);
/* viewHolder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, Object> item = models.get(position);
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
// Make sure you put example png image named myImage.png in your
// directory
String imagePath = Environment.getExternalStorageDirectory()
+ "/108.png";
String imagePath = (String)item.get("IMAGE");
Toast.makeText(context, imagePath, Toast.LENGTH_LONG).show();
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share, "Share Image!"));
}
});*/
// viewHolder.share.setOnItemClickListener(this);
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
// viewHolder.countt = (TextView) v.findViewById(R.id.count);
HashMap<String, Object> item = models.get(position);
isSelected = (Boolean) item.get("selected");
item.put("selected", !isSelected);
notifyDataSetChanged();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
final HashMap<String, Object> item = getItem(position);
// like = (ImageView) view.findViewById(R.id.like);
//sharingButton = (ImageButton) view.findViewById(R.id.share);
// final HashMap<String, Object> item1 = getItem(position);
isSelected = (Boolean) item.get("selected");
if (isSelected) {
viewHolder.like.setBackgroundResource(R.drawable.checked);
} else {
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}
pic = (ImageView) view.findViewById(R.id.profilePic);
name = (TextView) view.findViewById(R.id.name);
idas = (TextView) view.findViewById(R.id.hpid);
idas2 = (TextView) view.findViewById(R.id.hpid2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
msg = (TextView) view.findViewById(R.id.txtStatusMsg);
url = (TextView) view.findViewById(R.id.txtUrl);
image = (ImageView) view.findViewById(R.id.feedImage1);
//countt =(TextView)view.findViewById(R.id.count);
/*if any exception raises please use
locationTitle.setText(((String)item.get(“NAME�?)));
use this technique for the Image also.
*/
//holder.like.setText(item.get(item));
//like.setText((String) item.get(R.id.like));
idas.setText((CharSequence) item.get("UIDAS"));
// listItems.add(idas.getText().toString());
name.setText((CharSequence) item.get("NAME"));
timestamp.setText((CharSequence) item.get("TIME"));
msg.setText((CharSequence) item.get("MSG"));
url.setText((CharSequence) item.get("URL"));
//countt.setText((CharSequence) item.get("COUN"));
//count.setText("" + count1);
int w = image.getWidth();
int h = image.getHeight();
if (w > 1000)
{
a=w-1000;
b=w-a;
}
else
{
b=w;
}
if (h > 1000)
{
a1=h-1000;
b1=h-a1;
}
else
{
b1=h;
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.placeholder(R.drawable.profile_dummy)
//.error(R.drawable.ic_whats_hot)
.resize(50, 50)
// .centerCrop()
// .fit()
.into(pic);
/*Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;*/
Picasso.with(context)
.load((String)item.get("IMAGE"))
//.load("IMAGE")
// .placeholder(R.drawable.ic_pages)
//.error(R.drawable.ic_home)
.resize(1000,b1)
.onlyScaleDown()
//.centerCrop()
// .fit().centerInside()
.into(image);
/*if ((image).length() < 0)
{
//image.setVisibility(View.VISIBLE);
// invalid = true;
idas2.setText(1);
// Toast.makeText(getApplicationContext(), "hgghghghjgh", Toast.LENGTH_LONG).show();
}*/
/* delam.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
// pacm = idas.getText().toString();
listItems.remove(index.intValue());
notifyDataSetChanged();
}
}
);
*/
/*
delam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pacm = idas.getText().toString();
removeItemFromList();
}
});
*/
/* like.setTag(position);
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// int p = (Integer)v.getTag();
//int p;
//int posit=(Integer)v.getTag();
//String s = view[position];
//Context get = null;
//Toast.makeText(context, String.valueOf(p) , Toast.LENGTH_LONG).show();
//like.setBackgroundResource(R.drawable.checked);
if( viewHolder.like.isSelected()){
viewHolder.like.setSelected(false);
//ctv.setBackgroundColor (Color.parseColor("#ffffff"));
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}else if(! viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
viewHolder.like.setBackgroundResource(R.drawable.checked);
}
}
});*/
return view;
}
// HashMap<String, Object> item = models.get(position);
}
Well try this, in your HashMap list you need to have one more item called selected to store selected row status
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
//your code
if (view == null) {
viewHolder = new ViewHolder();
//your code
//add below code after (end of) your code
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
HashMap<String, Object> item = models.get(position);
boolean isSelected = (boolean) item.get("selected");
item.put("selected", !isSelected);
notifyDataSetChanged();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
//updated
viewHolder.like.setTag(position);
final HashMap<String, Object> item = getItem(position);
boolean isSelected = (boolean) item.get("selected");
if (isSelected) {
viewHolder.like.setBackgroundResource(R.drawable.checked);
} else {
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}
//your other code
}
This problem is due to recycling of Viewholder object in your ListView through convertView. Do not make logic based on the view state as the same state can be passed to some another item of ListView, where it supposed to be presented.
So what to do?
Hold your state on your data Item. And use notify dataSetChanged when you click some item not change its background Directly.
You can see example here. That one id for RecyclerView Adapter, but concept is same. RecyclerView causes issue when recycling

Android:How to sort list by date in android

I have a list view with many list items.Each list item contains testname,test enddate and no. of questions.I want to sort the list items according to dates.The dates which have expired are in grey color and new test dates are black. I am attaching the code which i have done till now.
can u please suggest me some code to do it.
public class Test_List_Adapter extends BaseAdapter {
public Activity context;
public String names[];
public String endDate[];
public String questions[];
public LayoutInflater inflater;
public Test_List_Adapter(Activity context, ArrayList<String> testid,
ArrayList<String> testName, ArrayList<String> endDate,
ArrayList<String> questions) {
this.context = context;
this.names = testName.toArray(new String[0]);
this.endDate = endDate.toArray(new String[0]);
this.questions = questions.toArray(new String[0]);
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
TextView testname;
TextView questions;
TextView testenddate;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder;
ViewHolder holder1 = null;
if (convertView == null) {
holder = new ViewHolder();
//inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.test_list_items,
null);
holder.testname = (TextView) convertView
.findViewById(R.id.testName);
holder.questions = (TextView) convertView
.findViewById(R.id.noofQuestions);
holder.testenddate = (TextView) convertView
.findViewById(R.id.testDate);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
final long date = System.currentTimeMillis();
Log.d("Current date", date + "");
long endtime = Constants.test_closetime.get(position);
endtime = TimeUnit.SECONDS.toMillis(endtime);
Log.v("end time of selected class is: ", endtime + "");
if (date < endtime) {
Log.d("color", "white");
convertView.setBackgroundColor(Color.BLACK);
holder.testenddate.setText(endDate[position]);
}
else
{
Log.d("color", "gray");
holder.testenddate.setText(endDate[position]);
convertView.setBackgroundColor(Color.DKGRAY);
}
/*for (int i = 0; i < Constants.test_closetime.size(); i++)
{
long endtime1 = Constants.test_closetime.get(i);
endtime1 = TimeUnit.SECONDS.toMillis(endtime1);
for (int j = i+1; j < Constants.test_closetime.size(); j++)
{
long endtime2 = Constants.test_closetime.get(j);
endtime2 = TimeUnit.SECONDS.toMillis(endtime2);
if(endtime1<endtime2)
{
long temp;
temp=endtime1;
endtime1=endtime2;
endtime2=temp;
holder.testenddate.setText(endDate[position]);
}
}
holder.testenddate.setText(endDate[position]);
}*/
holder.testenddate.setText(endDate[position]);
holder.testname.setText(names[position]);
holder.testenddate.setText(endDate[position]);
holder.questions.setText(questions[position]);
Log.v("exiting =test list adapter", "true");
Log.v("exiting =test list adapter", "return convertview");
} catch (Exception e) {
Log.e("Test_List_Adapter/getView()", e.toString());
e.printStackTrace();
}
return convertView;
}
}
Create a container class for one list item that contains name, endDate and question.
Instead of having three string arrays, have one ArrayList that contains those containers.
Sort that ArrayList using Collections.sort(List, Comparator)
Let us know if you need specific help with any of those steps.
Extra credit:
Use a Date object instead of a string to represent dates.

Pass a variable value from Base Adapter to activity

I have a set a variable in my Base Adapter class, now I want to get(pass) this variable in my related Activity. I am not getting how to do this.
Here is my code.
public class TourDescAdapter extends BaseAdapter {
private List<Descriptions> descriptList;
private LayoutInflater mInflater;
ViewHolder holder;
#SuppressWarnings("unused")
private OnClickListener clickListener;
Activity context;
//TourDescription tourDesc;
ArrayList<HashMap<String, Object>> obj = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> discountedTourDetails = null;
String price = null, prodId = null;
String promoTourname, tourName;
public TourDescAdapter(List<Descriptions> descriptList,
TourDescription activity) {
this.context = activity;
this.descriptList = descriptList;
mInflater = LayoutInflater.from(activity);
clickListener = (OnClickListener) activity;
}
#Override
public int getCount() {
return this.descriptList.size();
}
#Override
public Object getItem(int position) {
return this.descriptList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.tourlist, null);
/****
* Creates a ViewHolder and store references to the two children
* views we want to bind data to
****/
holder = new ViewHolder();
holder.rlayout = (RelativeLayout) convertView
.findViewById(R.id.tourlayout);
holder.title = (TextView) convertView
.findViewById(R.id.tourtitletext);
holder.desc = (TextView) convertView.findViewById(R.id.tourdes);
holder.amountButton = (Button) convertView
.findViewById(R.id.amtBtn);
holder.pinButton = (Button) convertView.findViewById(R.id.pinBtn);
holder.arrowButton = (Button)convertView.findViewById(R.id.arrowBtn);
holder.serialText = (EditText)convertView.findViewById(R.id.pinText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText((String) descriptList.get(position)
.getImageTitle());
holder.desc.setText((String) descriptList.get(position)
.getImageDescription());
((ImageView) holder.rlayout.getChildAt(0)).setImageBitmap(BitmapFactory
.decodeFile((RaconTours.PATH + RaconTours.city + File.separator
+ TourDescription.currentTour.getObjtourName()
+ File.separator + descriptList.get(position)
.getImagePath().split("/")[2]).replace(" ", "_")));
if (position == 0) {
SharedPreferences settings = context.getSharedPreferences("downloadDetails", 0);
String isTourDownloaded = settings.getString(TourDescription.currentTour.getObjtourName(), "");
if (isTourDownloaded.equals("true")) {
//if (!(TourDescription.downloadFile.exists())||TourDescription.downloadFile.exists() == false ) {
//if (TourDescription.currentTour.getIsTourDownloaded() == true) {
//holder.pinButton.setVisibility(View.INVISIBLE);
//holder.arrowButton.setVisibility(View.INVISIBLE);
//holder.serialText.setVisibility(View.INVISIBLE);
}
holder.amountButton.setVisibility(View.VISIBLE);
holder.amountButton.setText("Start");
} else {
File promoPlistPath = new File(RaconTours.PATH + "promocode.txt");
checkPromoCode(promoPlistPath);
if (discountedTourDetails != null) {
tourName = (String) discountedTourDetails.get("promoTour");
price = (String) discountedTourDetails.get("discountPrice");
prodId = (String) discountedTourDetails.get("disProId");
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText("$" +price);
//promoPlistPath.delete();
} else {
// Enabling the two buttons
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText(TourDescription.currentTour
.getObjPrice());
}
}
} else {
holder.amountButton.setVisibility(View.INVISIBLE);
holder.pinButton.setVisibility(View.INVISIBLE);
holder.arrowButton.setVisibility(View.INVISIBLE);
holder.serialText.setVisibility(View.INVISIBLE);
holder.title.setBackgroundColor(Color.WHITE);
holder.title.setTextColor(Color.BLACK);
holder.title.setGravity(Gravity.CENTER_HORIZONTAL);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.INVISIBLE);
}
return convertView;
}
#SuppressWarnings("unchecked")
private void checkPromoCode(File promoPlistPath) {
if (promoPlistPath.exists()) {
try {
ObjectInputStream inStream = new ObjectInputStream(
new FileInputStream(promoPlistPath));
obj = (ArrayList<HashMap<String, Object>>) inStream
.readObject();
for (HashMap<String, Object> tmpObj : obj) {
promoTourname = (String) tmpObj.get("promoTour");
if (promoTourname.equals(TourDescription.currentTour.getObjtourName())) {
discountedTourDetails = tmpObj;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ViewHolder {
Button pinButton;
Button amountButton;
RelativeLayout rlayout;
TextView title;
TextView desc;
Button arrowButton;
EditText serialText;
}
}
Here
prodId = (String) discountedTourDetails.get("disProId");
I want to pass prodId to related activity.
Note: Base Adapter is called from the activity
adapter = new TourDescAdapter(currentTour.getListOfDescriptions(), this);
setListAdapter(adapter);
Any one can tell me how to do this?
Couldn't you just use String iGotTheString = adapter.prodId?

Categories

Resources