Updating ListView items with AsyncTask - android

I have the follow scenario:
One activity that consults values from internet and fills an object below:
public class LPBean {
private Lin lin;
private Posted posted;
public Lin getLin() {
return lin;
}
public void setLin(Lin lin) {
this.lin = lin;
}
public Posted getPosted() {
return posted;
}
public void setEstimativa(Posted p) {
this.posted = p;
}
}
My activity fill the lin information in LPBean from internet and pass the object to CustomAdapter
But the posted value from LPBean is populated with information from the internet and the search key is lin.id (form LPBean),so tho do this, I'm using a AsynkTask.
Thus, the listView is showing to user and the posted values (from LpBean) are displayed dynamically with listView opened.
To do this, I make like below:
public class ListaLinsAdapter extends BaseAdapter {
private Context context;
private List<LinPostedBean> lins;
private LayoutInflater inflater;
private ViewHolder holder;
private String idLin;
public ListaLinsAdapter(Context context, List<LinPostedBean> listaLins) {
this.context = context;
this.lins = listaLins;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lins.size();
}
#Override
public Object getItem(int position) {
return lins.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// Recupera o estado da posição atual
LinPostedBean lpBean = lins.get(position);
Lin lin = lpBean.getLin();
do somthing.....
and at the end of the getView method from adapter, is verified if has value to posted attribute to show the information
if((lpBean.getPosted() != null) && (lpBean.getPosted().getPonto() != null))
{
if(lpBean.getPosted().getPonto().size() > 0)
holder.fillPosted(lpBean.getPosted());
else
holder.showMsg(context.getResources().getString(R.string.msgEmptyPosted));
}
return view;
}
In my activity I have implemented the AsyncTask inner class like below:
private class ConsultaPostedBackGround extends AsyncTask<Object, Void, Object[]> {
#Override
protected Object[] doInBackground(Object... objs) {
try {
LinPostedBean lpBean = (LinPostedBean)objs[0];
Context context = (Context)objs[3];
String linId = lpBean.getLin().getLin();
int indice = linId.indexOf("-");
linId = linId.substring(0,indice).trim();
//GET INFORMATION FROM INTERNET
PostedUtil pUtil = new PostedUtil(pontoId.trim(), linId,
context);
//PUT INTERNET RESULT IN Posted ATTRUBUTE IN ADAPTER
Integer position = (Integer)objs[1];
((LinPostedBean)((ListaLinsAdapter)objs[2]).getItem(position)).setEstimativa(pUtil.getPosted());
} catch (Exception e) {
objs[3] = null;
}
return objs;
}
#Override
protected void onPostExecute(Object[] result) {
//REFRESH LISTVIEW
if(result[3] != null)
((ListaLinsAdapter)result[2]).notifyDataSetChanged();
}
In the activity I'm call the AsyncTask one time to each lin, like below:
ListView lista = (ListView) findViewById(R.id.listView);
lista.setAdapter(listaLinsAdapter);
lista.setOnItemClickListener(this);
int cont = 0;
for (LinPostedBean lpBean : listaLPBean) {
Object[] params = new Object[4];
params[0] = lpBean;
params[1] = new Integer(cont);
params[2] = listaLinsAdapter;
params[3] = this;
//CALL TO AsyncTask
new ConsultaPrevisaoBackGround().execute(params);
cont++;
}
I think that this strategy are correct, but not working. The values of posted is not
showing in listview.
What is wrong??
UPDATED
My class Adapter:
public class ListaLinsAdapter extends BaseAdapter {
private Context context;
private List<LinPostedBean> lins;
private LayoutInflater inflater;
private ViewHolder holder;
private String idLin;
public ListaLinsAdapter(Context context, List<LinPostedBean> listaLins) {
this.context = context;
this.lins = listaLins;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lins.size();
}
#Override
public Object getItem(int position) {
return lins.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// Recupera o estado da posição atual
LinPostedBean lpBean = lins.get(position);
Lin lin = lpBean.getLin();
if (view == null) {
view = inflater.inflate(R.layout.listadadoslins, null);
holder = new ViewHolder(context);
// Número da lin
holder.txtIdLin = (TextView) view.findViewById(R.id.txtIdLin);
// Nome da lin
holder.txtNomeLin = (TextView) view
.findViewById(R.id.txtNomeLin);
// Seta campo de informação sem parada
holder.txtMsgSemParada = (TextView) view
.findViewById(R.id.msgSemParada);
// seta layouts de previsão
holder.llLin1 = (LinearLayout) view
.findViewById(R.id.linearPrevisoes1);
holder.llLin2 = (LinearLayout) view
.findViewById(R.id.linearPrevisoes2);
holder.llLin3 = (LinearLayout) view
.findViewById(R.id.linearPrevisoes3);
// Seta campos de previsão
holder.txtPrev1 = (TextView) view.findViewById(R.id.txtPrev1);
holder.txtPrev2 = (TextView) view.findViewById(R.id.txtPrev2);
holder.txtPrev3 = (TextView) view.findViewById(R.id.txtPrev3);
holder.txtPrev4 = (TextView) view.findViewById(R.id.txtPrev4);
holder.txtPrev5 = (TextView) view.findViewById(R.id.txtPrev5);
holder.txtPrev6 = (TextView) view.findViewById(R.id.txtPrev5);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.reset();
}
String lin = lin.getLin().trim();
StringTokenizer stk = new StringTokenizer(lin, "-");
// Número da lin
idLin = stk.nextToken();
holder.txtIdLin.setText(idLin);
// Nome da lin
holder.txtNomeLin.setText(stk.nextToken());
//new ConsultaPostedBackGround().execute("");
if((lpBean.getPosted() != null) && (lpBean.getPosted().getPonto() != null))
{
if(lpBean.getPosted().getPonto().size() > 0)
holder.fillPosted(lpBean.getPosted());
else
holder.showMsg(context.getResources().getString(R.string.msgSemPosted));
}
return view;
}
static class ViewHolder {
Context context;
TextView txtIdLin;
TextView txtNomeLin;
TextView txtMsgSemParada;
LinearLayout llLin1;
LinearLayout llLin2;
LinearLayout llLin3;
TextView txtPrev1;
TextView txtPrev2;
TextView txtPrev3;
TextView txtPrev4;
TextView txtPrev5;
TextView txtPrev6;
public ViewHolder(Context cont) {
this.context = cont;
}
public void reset() {
txtIdLin.setText(null);
txtNomeLin.setText(null);
limpaPrevisoes();
}
private void limpaPrevisoes() {
llLin1.setVisibility(View.GONE);
llLin2.setVisibility(View.GONE);
llLin3.setVisibility(View.GONE);
txtMsgSemParada.setVisibility(View.GONE);
txtPrev1.setText(null);
txtPrev2.setText(null);
txtPrev3.setText(null);
txtPrev4.setText(null);
txtPrev5.setText(null);
txtPrev6.setText(null);
}
public void showError() {
showMsg(context.getResources().getString(R.string.msgErroPosted));
}
public void showMsg(String msg) {
limpaPrevisoes();
txtMsgSemParada.setText(msg);
}
public void fillPosted(Posted p) {
Collections.sort(p.getPonto());
if (p.getPonto().size() > 6) {
for (int i = 6; i < p.getPonto().size(); i++)
p.getPonto().remove(i);
}
int cont = 1;
for (Estimativa estimativa : p.getPonto()) {
setPosted(cont, estimativa, p);
cont++;
}
if (p.getPonto().size() <= 2) {
llLin2.setVisibility(View.GONE);
llLin3.setVisibility(View.GONE);
}
if ((p.getPonto().size() > 2) && (p.getPonto().size() <= 4))
llLin3.setVisibility(View.GONE);
}
// Preenche o campo referente à estimativa
private void setPosted(int id, Estimativa estimativa,
Posted posted) {
switch (id) {
case 1:
txtPrev1.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev1);
break;
case 2:
txtPrev2.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev2);
break;
case 3:
txtPrev3.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev3);
break;
case 4:
txtPrev4.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev4);
break;
case 5:
txtPrev5.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev5);
break;
case 6:
txtPrev6.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev6);
break;
default:
break;
}
}
private String getgetPostedFormatedPosted(Posted posted,
Estimativa estimativa) {
String hourStr;
String minutoStr;
long hourAtual = Long.parseLong(posted.getHorarioAtual());
long seconds = (estimativa.getHorarioPacote() - hourAtual) / 1000;
int week = (int) Math.floor(seconds / 604800);
seconds -= week * 604800;
int dias = (int) Math.floor(seconds / 86400);
seconds -= dias * 86400;
int hours = (int) Math.floor(seconds / 3600);
seconds -= hours * 3600;
int minutes = (int) Math.floor(seconds / 60);
seconds -= minutes * 60;
minutes += 1;
if (hours < 10)
hourStr = "0" + hours;
else
hourStr = String.valueOf(hours);
if (minutes < 10)
minutoStr = "0" + minutes;
else
minutoStr = String.valueOf(minutes);
String tempo;
if (hours > 0)
tempo = hourStr + "h " + minutoStr + "min";
else
tempo = minutoStr + "min";
SimpleDateFormat spf = new SimpleDateFormat("HH:mm:ss");
tempo = tempo + " às "
+ spf.format(estimativa.getHorarioEstimado());
return tempo;
}
private void setBackGroundColor(Estimativa estimativa, TextView txtView) {
// Imagem a ser exibida
switch (estimativa.getStatus()) {
case 0:
txtView.setBackgroundColor(context.getResources().getColor(
R.color.postedVerde));
break;
case 1:
txtView.setBackgroundColor(context.getResources().getColor(
R.color.postedLaranja));
break;
case 2:
txtView.setBackgroundColor(context.getResources().getColor(
R.color.postedVermelha));
break;
default:
break;
}
}
}
}
My xml of a item in listView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtIdLinha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="6dp"
android:paddingRight="4dp"
android:paddingTop="4dp"
android:text="184"
android:textColor="#color/blue_nightsky"
android:textSize="20sp"
android:textStyle="bold" />
<LinearLayout
android:id="#+id/llPrevisoes"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearTit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/txtNomeLinha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="7dp"
android:text="FFFFFF"
android:textColor="#drawable/dialog_itemtextlist_selector"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/msgSemParada"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="7dp"
android:text="#string/msgSemPrevisao"
android:textColor="#drawable/dialog_itemtextlist_selector"
android:textSize="12sp"
android:textStyle="bold"
android:visibility="gone" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearPrevisoes1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp">
<TextView
android:id="#+id/txtPrev1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
<TextView
android:id="#+id/txtPrev2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearPrevisoes2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp" >
<TextView
android:id="#+id/txtPrev3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
<TextView
android:id="#+id/txtPrev4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearPrevisoes3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp">
<TextView
android:id="#+id/txtPrev5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
<TextView
android:id="#+id/txtPrev6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
UPDATED
Solved, the problem was in my adapter.

Try adding the following to your ListaLinsAdapter.
public void add(LinPostedBean lpb){
lins.add(lpb);
notifyDataSetChanged();
}
Then call that in doInBackground and you don't need to use onPostExecute in this case.

Related

How to update imageview from the parent recyclerview after click on nested recyclerview's imageview

Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.
Parent Recyclerview Adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String itemTitle = dataList.get(i).getTitle();
final String itemDescription = dataList.get(i).getDescription();
ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();
itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle, expandImage;
protected ImageView bookmarkImage,largeImage;
protected RecyclerView recyclerSmallImageList;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.title);
this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
this.largeImage = (ImageView) view.findViewById(R.id.large_image);
this.expandImage = (TextView) view.findViewById(R.id.expand);
this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);
}
}
}
Nested Recyclerview Adapter:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SmallImages> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SmallImages singleItem = itemsList.get(i);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
//this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.
/////Adapter class
public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {
private Context mContext;
private int rowLayout;
private List<ModelRouteDetailsUp> dataMembers;
private ArrayList<ModelRouteDetailsUp> arraylist;
private ArrayList<ModelKidDetailsUp> arraylist_kids;
List<String> wordList = new ArrayList<>();
Random rnd = new Random();
int randomNumberFromArray;
private ModelRouteDetailsUp personaldata;
private ProgressDialog pDialog;
private ConnectionDetector cd;
String img_baseurl = "";
String item = "";
public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
this.mContext = mcontext;
this.rowLayout = rowLayout;
this.dataMembers = tripList;
wordList.clear();
this.img_baseurl = img_baseurl;
arraylist = new ArrayList<>();
arraylist_kids = new ArrayList<>();
arraylist.addAll(dataMembers);
cd = new ConnectionDetector(mcontext);
pDialog = KPUtils.initializeProgressDialog(mcontext);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new AdapterTodayTrip.VHItem(v);
}
#Override
public int getItemCount() {
return dataMembers.size();
}
#Override
public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
try {
personaldata = dataMembers.get(position);
if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
}
****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
if (personaldata.getKidlist().size() > 0) {
viewHolder.linear_childview.setVisibility(View.VISIBLE);
viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
viewHolder.id_gallery.removeAllViews();
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(0, 0, 8, 0);
LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < personaldata.getKidlist().size(); i++) {
View view = layoutInflater.inflate(R.layout.view_child_list, null);
view.setLayoutParams(buttonLayoutParams);
RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);
TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
int count = i + 1;
String count1 = "0";
if (count <= 10) {
count1 = "0" + count;
}
tv_count.setText(String.valueOf(count1));
viewHolder.id_gallery.addView(view);
final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
if(!baseurl.isEmpty()) {
iv_circular.setTag(baseurl);
}
if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
bgShape.setColor(Color.parseColor("#A6b1a7a6"));
rl_txt.setVisibility(View.GONE);
//rl_img.setVisibility(View.VISIBLE);
tv_name.setVisibility(View.GONE);
Log.d("aimg_baseurl", baseurl);
try {
Picasso.with(mContext)
.load(baseurl)
.resize(60,60)
.centerCrop()
.into(iv_circular);
iv_circular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url=iv_circular.getTag().toString().trim();
if(!url.isEmpty())
KPUtils.showToastShort(mContext,url);
Picasso.with(mContext)
.load(url)
.resize(60,60)
.centerCrop()
.into(viewHolder.img_child);
}
});
} catch (Exception e) {
}
} else {
}
}
}else{
viewHolder.linear_childview.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class VHItem extends RecyclerView.ViewHolder {
CardView cv_members;
ImageView img_child;
TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
LinearLayout id_gallery,linear_childview;
public VHItem(View itemView) {
super(itemView);
img_child= (ImageView) itemView.findViewById(R.id.img_child);
cv_members = (CardView) itemView.findViewById(R.id.cv_members);
tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
}
}
}
/////////////////////////// this layout is inflated in every row
view_child_list
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/iv_circular"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#d27959"
app:civ_border_width="1dp" />
<RelativeLayout
android:id="#+id/rl_txt"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="gone">
<com.app.kidpooldriver.helper.CircularTextView
android:id="#+id/tv_name"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="70dp"
android:layout_height="70dp"
android:gravity="center"
android:text="01"
android:textColor="#color/white"
android:textSize="35sp"
tools:ignore="MissingPrefix" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="visible">
<TextView
android:id="#+id/tv_count"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="01"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#ffffff"
android:textStyle="bold"
tools:ignore="MissingPrefix" />
</RelativeLayout>
</FrameLayout>
///// this is the mianlayout which is inflated.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin"
android:elevation="#dimen/elevation"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/main_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:layout_marginTop="#dimen/fifteen"
android:orientation="horizontal"
android:paddingLeft="#dimen/ten">
<TextView
android:id="#+id/tv_trip_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#KD09201701"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/twenty"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_trip_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/light_green"
android:gravity="center"
android:padding="5dp"
android:text="In Progress"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
</LinearLayout>
<TextView
android:id="#+id/tv_vehicle_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:text="Route 26U-26D"
android:visibility="gone"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/route_textcolor" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_trip_start_time"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="06:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor" />
<TextView
android:id="#+id/tv_trip_end_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="08:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/tv_trip_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:visibility="gone"
android:paddingRight="20dp"
android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/grey_textcolor"
android:textStyle="normal" />
<ImageView
android:id="#+id/img_child"
android:layout_width="200dp"
android:layout_gravity="center"
android:layout_height="200dp" />
<LinearLayout
android:id="#+id/linear_childview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fifteen"
android:orientation="horizontal">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:scrollbars="none">
<LinearLayout
android:id="#+id/id_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
<LinearLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/ly_ring_circular"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_total_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:ignore="MissingPrefix"
fontPath="fonts/Poppins-Bold.ttf"
android:text="+20"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
/////POJO CLASS &json parsing & Adapter /////
public class ModelRouteDetailsUp {
String city_id;
String area_name;
String area_status;
String is_active;
String areas;
private ArrayList<ModelKidDetailsUp> kidlist;
///////this is the kid list
public ArrayList<ModelKidDetailsUp> getKidlist() {
return kidlist;
}
public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
this.kidlist = kidlist;
}
}
**///json parsing.......**
public boolean addRideDetails(JSONObject jsonObject) {
Boolean flag = false;
String isstatus = "";
if (jsonObject != null && jsonObject.length() > 0) {
try {
JSONArray mainArray = jsonObject.getJSONArray("schedules");
for (int i = 0; i < mainArray.length(); i++) {
ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
JSONObject c = mainArray.getJSONObject(i);
////// For Route Details //////
JSONObject route_details = c.getJSONObject("route_details");
modelRouteDetails.setDs_id(route_details.optString("ds_id"));
modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
modelRouteDetails.setRoute_id(route_details.optString("route_id"));
modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
modelRouteDetails.setStart_time(route_details.optString("start_time"));
modelRouteDetails.setEnd_time(route_details.optString("end_time"));
////// For Allotted Kids //////
JSONArray kidArray = c.getJSONArray("alloted_kids");
ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
if (kidArray.length() > 0) {
for (int j = 0; j < kidArray.length(); j++) {
ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
JSONObject kidObject = kidArray.getJSONObject(j);
kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
genre.add(kidDetailsUp);
}
}
///////add the kidlist here
modelRouteDetails.setKidlist(genre);
////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
**/////adapter callfrom class**
private void showData() {
if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
rv_trip_list.setAdapter(adapterTodayTrip);
}else {
tv_msg.setVisibility(View.VISIBLE);
}
}
Generally, the solution is to pass custom interface listener into the nested adapter and than the nested adapter will report any time one of his item clicked.
1.
You can create interface like:
public interface INestedClicked {
onNestedItemClicked(Drawable drawble)
}
2.
Pass in the constructor of SectionListDataAdapter a INestedClicked:
SectionListDataAdapter itemListDataAdapter = newSectionListDataAdapter(mContext, singleSectionItems, new INestedClicked() {
#Override
void onNestedItemClicked(Drawable drawble) {
// Do whatever you need after the click, you get the drawable here
}
});
In the constructor of SectionListDataAdapter save the instance of the listener as adapter parameter
private INestedClicked listener;
4.
When nested item clicked report the listener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onNestedItemClicked(imageView.getDrawable());
}
}

RecyclerView Displays only last objects in List

I am trying to display data in a RecyclerView. I have created an adapter to handle the RecyclerViews from different activities. The issue I am facing is displaying the data appropriately. So far I can only display the last elements in the list. In this case, the last candidate for each ContestedOffice. I have attached my code for both the activity and adapter as well as a screenshot of the output.
My Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String LOGCAT = RecyclerAdapter.class.getSimpleName();
private static final int VIEW_TYPE_VOTE = 0;
private static final int VIEW_TYPE_PREVIEW = 1;
private List candidatesList;
private LinearLayout checkBoxParent;
private VoteActivity voteActivity;
private Context context;
public RecyclerAdapter(List candidatesList) //Generic List
{
this.candidatesList = candidatesList;
}
#Override
public int getItemViewType(int position) {
if (candidatesList.get(position) instanceof Candidate) {
return VIEW_TYPE_PREVIEW;
} else {
return VIEW_TYPE_VOTE;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
if (viewType == VIEW_TYPE_PREVIEW) {
View preview = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_candidate_recycler, parent, false);
return new CandidateViewHolder(preview); // view holder for candidates items
} else if (viewType == VIEW_TYPE_VOTE) {
View ballot = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_ballot_view, parent, false); //false too
return new BallotViewHolder(ballot); // view holder for ContestedOffice items
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final int itemType = getItemViewType(position);
if (itemType == VIEW_TYPE_PREVIEW) {
CandidateViewHolder.class.cast(holder).bindData((Candidate)
candidatesList.get(position));
} else if (itemType == VIEW_TYPE_VOTE) {
BallotViewHolder.class.cast(holder).bindData((ContestedOffice)
candidatesList.get(position));
}
}
#Override
public int getItemCount() {
Log.d(LOGCAT, " Size: " + candidatesList.size());
return candidatesList.size();
}
/**
* ViewHolder class
*/
private class BallotViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private AppCompatTextView vote_candidate_name;
private AppCompatTextView vote_candidate_details;
private AppCompatTextView vote_candidate_party;
BallotViewHolder(View view) {
super(view);
checkBoxParent = (LinearLayout) view.findViewById(R.id.checkbox_layout_parent);
vote_candidate_name = (AppCompatTextView) view.findViewById(R.id.vote_candidate_name)
vote_candidate_party = (AppCompatTextView) view.findViewById(R.id.vote_candidate_party);
vote_candidate_details = (AppCompatTextView) view.findViewById(R.id.vote_candidate_details);
}
void bindData(ContestedOffice candidate)
{
int length = candidate.getList().size();
Log.d(LOGCAT, "BallotList size:" + length);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
//params.setMargins(10, 10, 10, 10);
params.gravity = Gravity.END;
CheckBox checkBox = null;
for (int i = 0; i < length; i++)
{
vote_candidate_name.setText(candidate.getList().get(i).getCandidateName());
vote_candidate_party.setText(candidate.getList().get(i).getParty());
vote_candidate_details.setText(candidate.getList().get(i).getDetails());
//Create checkboxes for each recycler view created
checkBox = new CheckBox(context);
checkBox.setTag(candidate.getList().get(i).getCandidateID());
checkBox.setId(candidate.getList().get(i).getCandidateID());
//checkBox.setText(R.string.checkBox_message);
checkBox.setText(String.valueOf(candidate.getList().get(i).getCandidateID()));
checkBox.setBackgroundColor(Color.RED);
Log.d(LOGCAT, "TAGS: " + checkBox.getTag() + " id: " + checkBox.getId());
}
if (checkBox != null) {
checkBox.setOnClickListener(this);
}
checkBoxParent.addView(checkBox, params);
}
#Override
public void onClick(View v) {
// Is the view now checked?
boolean checked = ((CheckBox) v).isChecked();
// Check which checkbox was clicked
switch (v.getId()) {
case 31:
if (checked) {
Log.d(LOGCAT, "Here:" + v.getTag().toString());
} else
break;
case 30:
if (checked) {
Log.d(LOGCAT, "Here:" + v.getTag().toString());
} else
break;
}
}
}
/**
* ViewHolder class
*/
private class CandidateViewHolder extends RecyclerView.ViewHolder {
private AppCompatTextView candidate_name;
private AppCompatTextView candidate_details;
private AppCompatTextView candidate_party;
private AppCompatTextView candidate_position;
// private AppCompatImageView candidate_image;
CandidateViewHolder(View view) {
super(view);
candidate_name = (AppCompatTextView) view.findViewById(R.id.candidate_name);
// candidate_image = (AppCompatImageView) view.findViewById(R.id.candidate_image);
candidate_position = (AppCompatTextView) view.findViewById(R.id.candidate_position);
candidate_party = (AppCompatTextView) view.findViewById(R.id.candidate_party);
candidate_details = (AppCompatTextView) view.findViewById(R.id.candidate_details);
}
void bindData(Candidate candidate)//Candidate
{
candidate_name.setText(candidate.getCandidateName());
candidate_position.setText(candidate.getPosition());
candidate_details.setText(candidate.getDetails());
candidate_party.setText(candidate.getParty());
// candidate_image.setImageBitmap(candidate.getCandidatePhoto());
}
}
}
My VoteActivity Class
public class VoteActivity extends AppCompatActivity implements View.OnClickListener
{
private static final String LOGCAT = VoteActivity.class.getSimpleName();
private AppCompatActivity activity = VoteActivity.this;
private RecyclerView vote_recycler_view;
private LinearLayout checkBoxParent;
private CheckBox vote_candidate_checkBox;
private AppCompatButton appCompatButtonVote;
private RecyclerAdapter recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
private Ballot ballot;
private List <ContestedOffice> ballotList = new ArrayList<>();
private List<Candidate> candidateList = new ArrayList<>();
private DatabaseHelper databaseHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote);
getSupportActionBar().setTitle("");
initViews();
initObjects();
initListeners();
}
private void initListeners()
{
appCompatButtonVote.setOnClickListener(this);
}
private void initObjects()
{
recyclerAdapter = new RecyclerAdapter(ballotList);
databaseHelper = new DatabaseHelper(this);
layoutManager = new LinearLayoutManager(activity);
vote_recycler_view.setLayoutManager(layoutManager);
vote_recycler_view.setItemAnimator(new DefaultItemAnimator());
vote_recycler_view.setHasFixedSize(true);
vote_recycler_view.setAdapter(recyclerAdapter);
getCandidates();
}
private void getCandidates()
{
new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
ballotList.clear();
candidateList.clear();
candidateList.addAll(databaseHelper.getAllCandidates());
createBallot();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
recyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
private void initViews()
{
checkBoxParent = (LinearLayout) findViewById(R.id.checkbox_layout_parent);
vote_recycler_view = (RecyclerView) findViewById(R.id.vote_recycler_view);
//vote_candidate_checkBox = (CheckBox) findViewById(R.id.vote_candidate_checkBox);
appCompatButtonVote = (AppCompatButton) findViewById(R.id.appCompatButtonVote);
}
public List<ContestedOffice> createBallot()
{
int candidateListSize = candidateList.size();
String position;
ArrayList<String> positionArray = new ArrayList<>();
ContestedOffice office;
//Looping through the candidates list and add all the positions being contested for
// to an array list.
for (int i = 0; i< candidateListSize; i++)
{
position = candidateList.get(i).getPosition();
positionArray.add(position);
}
//Create a set to remove all duplicate positions
Set<String> noDuplicates = new HashSet<>();
noDuplicates.addAll(positionArray);
positionArray.clear();
positionArray.addAll(noDuplicates);
Log.d(LOGCAT, "Contested Offices and Candidates: " + positionArray.size() + " "+ candidateListSize);
//Create the Contested Office according to the size of the position array
//and make sure the names are added.
int noOfContestedOffice = positionArray.size();
for(int i = 0; i<noOfContestedOffice; i++)
{
office = new ContestedOffice(positionArray.get(i));
Log.d(LOGCAT, "New Contested Office Created:" + office.getName());
Candidate c = new Candidate();
for(int j = 0; j < candidateListSize; j++)
{
//All the Seats/Position being Contested For
String candidatePosition = candidateList.get(j).getPosition();
String contestedOfficeName = office.getName();
if(candidatePosition.equals(contestedOfficeName)) {
c = candidateList.get(j);
//Add the candidate to the Contested Office
office.add(c);
}
Log.d(LOGCAT, "Added Candidate: "+ candidateList.get(j) +" to: "+ office.getName());
}
//Add offices to ballot and ballot List
ballot = new Ballot();
ballot.add(office);
//Ideally Ballot into BallotList
ballotList.add(office);
Log.d(LOGCAT, "Office definitely added to ballotList: " + ballotList.size());
}
return ballotList;
}
}
My VoteActivity XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/colorBackground"
android:orientation="vertical"
tools:context=".activities.VoteActivity">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/colorPrimary"
android:gravity="center"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dashboard_vote_message"
android:textAlignment="center"
android:textSize="20sp" />
<android.support.v7.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textAlignment="center"
android:id="#+id/vote_message_placeholder"
android:text="#string/vote_message" />
</android.support.v7.widget.LinearLayoutCompat>
<include layout="#layout/fragment_ballot_layout"/>
<include layout="#layout/footer_vote_button" />
</LinearLayout>
RecyclerView XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/recycler_layout_parent"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_marginTop="5dp">
<android.support.v7.widget.RecyclerView
android:layout_weight="1"
android:id="#+id/vote_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"/>
</LinearLayout>
</LinearLayout>
CardView XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
xmlns:tools="http://schemas.android.com/tools"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/vote_candidate_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_vertical"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:src = "#drawable/btn_ballot"
android:textColor="#android:color/white"
android:textSize="16sp"
tools:text="8.9"
android:contentDescription="#string/candidate_photo" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/vote_candidate_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:maxLines="1"
android:textAllCaps="true"
android:textColor="#color/textColorCandidateName"
android:textSize="12sp"
tools:text="CANDIDATE NAME" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/vote_candidate_party"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textColorPartyDetails"
android:textSize="12sp"
android:ellipsize="end"
tools:text="PARTY NAME" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/vote_candidate_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:textColor="#color/textColorDetails"
android:textSize="16sp"
tools:text="Long placeholder for candidate details. 2 Lines Max" />
</LinearLayout>
<LinearLayout
android:id="#+id/checkbox_layout_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:orientation="vertical">
<!--Dynamic Checkboxes here-->
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Code Output
i think you are creating object of candidate every time in for loop make below chnages it will solve your problem
Candidate c = new Candidate();
ballot = new Ballot();
for(int i = 0; i<noOfContestedOffice; i++)
{
office = new ContestedOffice(positionArray.get(i));
Log.d(LOGCAT, "New Contested Office Created:" + office.getName());
for(int j = 0; j < candidateListSize; j++)
{
//All the Seats/Position being Contested For
String candidatePosition = candidateList.get(j).getPosition();
String contestedOfficeName = office.getName();
if(candidatePosition.equals(contestedOfficeName)) {
c = candidateList.get(j);
//Add the candidate to the Contested Office
office.add(c);
}
Log.d(LOGCAT, "Added Candidate: "+ candidateList.get(j) +" to: "+ office.getName());
}
//Add offices to ballot and ballot List
ballot.add(office);
//Ideally Ballot into BallotList
ballotList.add(office);
Log.d(LOGCAT, "Office definitely added to ballotList: " + ballotList.size());
}
just check it once and you are done with your problem.
i have update xml below
<android.support.v7.widget.RecyclerView
android:layout_weight="1"
android:id="#+id/vote_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
check it out the height of recyclerview.

Listview update another raw on update of selected raw

I working on one Shopping Cart application.
In which i show list of products and in that every raw there is "Add to Cart" button,
Whenever user clicks on it then that button goes to disable and another view which holds add and subtract quantity should be display.
But when i clicks on any single product "Add to Cart" button then that view is going to be update, But when i scroll listview then another view gets update automatically (Not all).
Adapter
public class CategoryProductListAdapter extends BaseAdapter {
Context context;
ArrayList<ProductDetailsModel> productDetailsModels;
FragmentManager fragmentManager;
LayoutInflater inflater;
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels) {
this.context = context;
this.productDetailsModels = productDetailsModels;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels,FragmentManager fragmentManager) {
this.context = context;
this.productDetailsModels = productDetailsModels;
this.fragmentManager = fragmentManager;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return productDetailsModels.size();
}
#Override
public Object getItem(int i) {
return productDetailsModels.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public class Holder {
LinearLayout llProductRawMain, llProductQty;
ImageView imgProduct;
TextView txtProductTitle, txtProductUnit;
Spinner spProductUnits;
Button btnAddProduct, btnSubProduct;
EditText etNoOfProduct;
TextView txtProductPrice;
Button btnAddToCart;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final Holder holder;
if (view == null) {
holder = new Holder();
view = inflater.inflate(R.layout.category_product_list_raw, viewGroup, false);
holder.llProductRawMain = (LinearLayout) view.findViewById(R.id.llProductRawMain);
holder.llProductQty = (LinearLayout) view.findViewById(R.id.llProductQty);
holder.imgProduct = (ImageView) view.findViewById(R.id.imgProduct);
holder.txtProductTitle = (TextView) view.findViewById(R.id.txtProductTitle);
holder.txtProductUnit = (TextView) view.findViewById(R.id.txtProductUnit);
holder.spProductUnits = (Spinner) view.findViewById(R.id.spProductUnits);
holder.btnAddProduct = (Button) view.findViewById(R.id.btnAddProduct);
holder.btnSubProduct = (Button) view.findViewById(R.id.btnSubProduct);
holder.etNoOfProduct = (EditText) view.findViewById(R.id.etNoOfProduct);
holder.txtProductPrice = (TextView) view.findViewById(R.id.txtProductPrice);
holder.btnAddToCart = (Button) view.findViewById(R.id.btnAddToCart);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.txtProductTitle.setText(Html.fromHtml(productDetailsModels.get(i).getName()));
if (productDetailsModels.get(i).getUnits().size() > 0) {
holder.txtProductUnit.setVisibility(View.GONE);
holder.spProductUnits.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(0).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(0).getPrice());
ArrayList<ProductUnitModel> units = new ArrayList<>();
units.clear();
units.addAll(productDetailsModels.get(i).getUnits());
ProductUnitsListAdapter productUnitsListAdapter = new ProductUnitsListAdapter(context, units);
holder.spProductUnits.setAdapter(productUnitsListAdapter);
holder.spProductUnits.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int j, long l) {
holder.etNoOfProduct.setText("1");
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(j).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(j).getPrice());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
holder.spProductUnits.setVisibility(View.GONE);
holder.txtProductUnit.setVisibility(View.VISIBLE);
holder.txtProductUnit.setText(productDetailsModels.get(i).getUnit());
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getImage(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getPrice());
}
holder.llProductRawMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (productDetailsModels.get(i).getUnits().size() > 0) {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", true);
intent.putExtra("productUnitPos", holder.spProductUnits.getSelectedItemPosition());
context.startActivity(intent);*/
//FragmentManager fragmentManager = fra;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = true;
int productUnitPos = holder.spProductUnits.getSelectedItemPosition();
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
} else {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", false);
intent.putExtra("productUnitPos", 0);
context.startActivity(intent);*/
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = false;
int productUnitPos = 0;
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
}
}
});
holder.btnAddProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty++;
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
}
});
holder.btnSubProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty--;
if (qty > 0) {
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
} else {
Toast.makeText(context, "Quntity can not be zero!", Toast.LENGTH_SHORT).show();
}
}
});
holder.btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final boolean isUserLogin = AppMethod.getBooleanPreference((Activity) context, AppConstant.PREF_IS_LOGGED_IN);
if (isUserLogin) {
holder.llProductQty.setVisibility(View.VISIBLE);
holder.btnAddToCart.setVisibility(View.GONE);
String product_id;
String variation_id;
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, 1);
} else {
Toast.makeText(context, "Please Login for Add to Cart !", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void updateCart(String product_id, String variation_id, int qty) {
String customer_id = AppMethod.getStringPreference((Activity) context, AppConstant.PREF_USER_ID);
if (AppMethod.isNetworkConnected((Activity) context)) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product_id", product_id);
jsonObject.put("variation_id", variation_id);
jsonObject.put("qty", qty);
jsonObject.put("customer_id", customer_id);
WsHttpPostJson wsHttpPostJson = new WsHttpPostJson(context, AppConstant.ADD_CART_WS, jsonObject.toString());
wsHttpPostJson.execute(AppConstant.ADD_CART_WS_URL);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
}
XML of Adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductRawMain"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:background="#drawable/product_grid_item_bg"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgProduct"
android:layout_width="match_parent"
android:layout_height="#dimen/_80sdp"
android:padding="#dimen/_5sdp"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:padding="#dimen/view_margin">
<TextView
android:id="#+id/txtProductTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:minLines="2"
android:textSize="#dimen/_11sdp"
android:text="Product Title"
android:textColor="#000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtProductUnit"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center_vertical"
android:padding="5dp"
android:textSize="#dimen/_11sdp"
android:text="Product Unit" />
<Spinner
android:id="#+id/spProductUnits"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center"
android:background="#drawable/icon_dropdown"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/txtProductPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="\u20B9 200"
android:textStyle="bold"
android:textSize="#dimen/_13sdp"
android:textColor="#185401" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductQty"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/app_color"
android:orientation="horizontal"
android:visibility="gone">
<Button
android:id="#+id/btnSubProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_minus"
android:gravity="center" />
<EditText
android:id="#+id/etNoOfProduct"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:background="#null"
android:ems="10"
android:enabled="false"
android:textSize="#dimen/_10sdp"
android:gravity="center"
android:inputType="number"
android:text="1"
android:textColor="#color/white" />
<Button
android:id="#+id/btnAddProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_plus"
android:gravity="center" />
</LinearLayout>
<Button
android:id="#+id/btnAddToCart"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/add_to_cart_btn_bg"
android:text="ADD TO CART"
android:textSize="#dimen/_12sdp"
android:textColor="#color/app_color" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I suffer from this also and realize that i think this links are help you.
Answer-1
Answer-2
Thanks

Circular imageview dissappears in listview after fling

Im generating a feed full of images (similar to instagram post) using Glide for loading images and user's profile picture. After i get the data from server, i load the Url's of images inside the listitem. Initally All items are being loaded properly.
The issue is that when i fast scroll the listview, user profile picture dissappears and that view doesnt respond to onClick Events. Please explain why this happens and how can i resolve this?
XML layout of each list Item.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:orientation="vertical" >
<RelativeLayout android:id="#+id/userheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/realdp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/nodp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/realdp"
android:text="handle"
android:layout_marginLeft="3dp"
android:gravity="center_vertical"
android:layout_alignTop="#+id/realdp"
android:layout_alignBottom="#+id/realdp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/uploadtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/handle"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:text="time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RelativeLayout android:id="#+id/rlimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/handle">
<ImageView
android:id="#+id/imgpost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:background="#ffffff"/>
</RelativeLayout>
<RelativeLayout android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rlimg"
android:layout_marginTop="5dp">
<com.sivaram.fishograph.FlipImageView
android:id="#+id/like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_marginLeft="20dp"
android:src="#drawable/hook_unlike"/>
<ImageButton
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_toRightOf="#+id/likesnum"
android:layout_marginLeft="20dp"
android:src="#drawable/comment" />
<ImageButton
android:id="#+id/more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_alignParentRight="true"
android:background="#00000000"
android:src="#drawable/more" />
<TextView
android:id="#+id/likesnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/like"
android:layout_alignTop="#+id/like"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/like"
android:text="likes"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
<TextView
android:id="#+id/comnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/comment"
android:layout_alignTop="#+id/comment"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/comment"
android:gravity="center_vertical"
android:text="comments"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/caption"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/userheader"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text="Caption"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/caption"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Java Code for generating feed:
public class Feed extends Fragment implements OnScrollListener
{
String handle;
ListView lvposts;
Jsparser jp;
int width,height;
int maxMemory;
int currentFirstVisibleItem ;
int currentVisibleItemCount;
PostAdapter pa;
ArrayList<eachpost> posts;
int value = 1;
boolean isLoading = false;
int photoid;
private List<String> myData;
Boolean tapped = false, Loading= false;
SharedPreferences spf;
ArrayList<String> likes;
public Feed()
{
super();
}
Feed(String handle)
{
super();
photoid = 99999999;
this.handle = handle;
}
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
spf = getActivity().getSharedPreferences("prefs",Context.MODE_PRIVATE);
likes = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup vg, Bundle b)
{
View v = inflater.inflate(R.layout.allposts, vg, false);
ActionBar ab = ((ActionBarActivity) getActivity()).getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.RED));
ab.hide();
lvposts = (ListView) v.findViewById(R.id.lvposts);
jp = new Jsparser();
Display d = getActivity().getWindowManager().getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
lvposts.setOnScrollListener(this);
posts = new ArrayList<eachpost>();
pa = new PostAdapter(getActivity(),R.layout.postcontent,posts,inflater);
Loading = true;
lvposts.setAdapter(pa);
new GetData(photoid).execute();
return v;
}
class GetData extends AsyncTask<String,String,String>
{
String msg;
Integer limit,success=0;
ProgressDialog pd;
Bitmap dpbm;
GetData(int l)
{
limit = l;
}
#Override
public void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> lp = new ArrayList<NameValuePair>();
lp.add(new BasicNameValuePair("handle",handle));
lp.add(new BasicNameValuePair("photoid",limit.toString()));
JSONObject job = jp.makeHttpRequest("server/getfeed.php", "POST", lp);
try
{
Log.d("json", job.toString());
success = job.getInt("success");
msg = job.getString("message");
if(success==1)
{
JSONArray ja = job.getJSONArray("posts");
for(int c = 0; c<ja.length(); c++)
{
JSONObject jb = ja.getJSONObject(c);
posts.add(new eachpost(jb.getString("handle"),jb.getString("url"), jb.getString("caption"),
jb.getString("uldatetime"), jb.getInt("likescount"), jb.getInt("comcount"), jb.getString("dpurl"), jb.getInt("isliked"),jb.getInt("photoid") ));
}
}
else
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
#Override
public void onPostExecute(String url)
{
Loading = false;
if(success==1)
{
photoid = posts.get(posts.size()-1).getPhotoid();
Log.d("last id",photoid+"");
Log.d("Length of posts",""+posts.size());
pa.notifyDataSetChanged();
}
}
}
class PostAdapter extends ArrayAdapter<eachpost>
{
ViewHolder vholder;
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File (root + ".feed");
Map<Integer,View> myViews;
public PostAdapter(Context context, int resource, ArrayList<eachpost> list, LayoutInflater li) {
super(context, R.layout.postcontent, list);
myViews = new HashMap<Integer,View>();
}
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
row.setTag(vholder);
myViews.put(pos, row);
}
return row;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
} //end of adapter class
static class ViewHolder {
TextView handle;
TextView caption;
TextView likesnum;
TextView comnum;
TextView uploadtime;
ImageView photo;
CircularImageView feeddp;
FlipImageView like;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.currentVisibleItemCount > 0 && scrollState == SCROLL_STATE_FLING) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(currentFirstVisibleItem > (currentVisibleItemCount - 2) && Loading!=true)
{
new GetData(photoid).execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
}
}
When loading multiple images there is always caching problem when using Async Tasks. I recommend an open source library Picasso. It will load the images and cache it. After that most probably, your fast scroll problem will solve.
The cause can also be the size of the images being received. Picasso has methods by which you can resize the image before putting it onto the image view
try with this modified getView
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
row.setTag(vholder); //changed here setTag()
}else{
vholder=(ViewHolder)row.getTag(); //changed here getTag()
}
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
myViews.put(pos, row);
}
return row;
}

Listview adapter doesnt show textview

I got a ListView Adapter. In this adapter , i fill it with some data .My problem is that it shows my date only after i scroll down and don't understand what's the problem , any ideas??
public class EventsAdapter extends ArrayAdapter<Article> {
EventsAdapter adapter = this;
Context context;
int layoutResourceId;
ArrayList<Article> cartItems = new ArrayList<Article>();
Date time;
public EventsAdapter(Context context, int layoutResourceId,
ArrayList<Article> galleries) {
super(context, layoutResourceId, galleries);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.cartItems = galleries;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Article eventItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.event_item_row, parent, false);
}
Typeface cFont2 = Typeface.createFromAsset(context.getAssets(), "fonts/berthold_baskerville_bold-webfont.ttf");
final RecordHolder holder = new RecordHolder();
holder.eventImage = (ImageView) convertView.findViewById(R.id.event_image);
holder.eventTitle = (TextView) convertView.findViewById(R.id.event_title);
holder.eventTitleDescription = (TextView) convertView.findViewById(R.id.event_title_description);
holder.eventCountries = (TextView) convertView.findViewById(R.id.event_countries);
holder.eventRegions = (TextView) convertView.findViewById(R.id.event_regions);
holder.eventCategory = (TextView) convertView.findViewById(R.id.event_category);
holder.eventType = (TextView) convertView.findViewById(R.id.event_type);
holder.eventDate = (TextView) convertView.findViewById(R.id.event_date);
holder.salary = (TextView) convertView.findViewById(R.id.job_salary);
holder.eventTitle.setTypeface(cFont2);
holder.salary.setVisibility(View.GONE);
holder.eventImage.setVisibility(View.GONE);
if (!eventItem.getImageURL().equals("")) {
holder.eventImage.setVisibility(View.VISIBLE);
Picasso.with(context)
.load(eventItem.getImageURL())
.resize(250, 175)
.into(holder.eventImage);
}
holder.eventTitle.setText(eventItem.getName());
if (eventItem.getCountry() == null) {
holder.eventCountries.setText(context.getString(R.string.all_countries));
} else {
holder.eventCountries.setText(eventItem.getCountry().getName());
}
if (eventItem.getRegion() == null) {
holder.eventRegions.setText(context.getString(R.string.all_regions));
} else {
holder.eventRegions.setText(eventItem.getRegion().getName());
}
boolean startDate = false;
boolean endDate = false;
String endDateString = "";
String startDateString = "";
for (int i = 0; i < eventItem.getExtraFields().size(); i++) {
if (eventItem.getExtraFields().get(i).getName().equals("EVENTENDDATE") && !eventItem.getExtraFields().get(i).getValue().getValue().equals("")) {
endDate = true;
endDateString = new SimpleDateFormat("dd/MM/yyyy").format(getDate(eventItem.getExtraFields().get(i).getValue().getValue()));
}
}
for (int i = 0; i < eventItem.getExtraFields().size(); i++) {
if (eventItem.getExtraFields().get(i).getName().equals("EVENTSTARTDATE") && !eventItem.getExtraFields().get(i).getValue().getValue().equals("")) {
startDate = true;
startDateString = new SimpleDateFormat("dd/MM/yyyy").format(getDate(eventItem.getExtraFields().get(i).getValue().getValue()));
}
}
if (startDate && endDate) {
holder.eventDate.setText(startDateString + " - " + endDateString);
holder.eventDate.setVisibility(View.VISIBLE);
} else if (startDate) {
holder.eventDate.setText(startDateString);
holder.eventDate.setVisibility(View.VISIBLE);
} else {
holder.eventDate.setVisibility(View.VISIBLE);
}
for (int i = 0; i < eventItem.getExtraFields().size(); i++) {
if (eventItem.getExtraFields().get(i).getName().equals("EVENTORGANISER")) {
holder.eventTitleDescription.setText(eventItem.getExtraFields().get(i).getValue().getValue());
} else if (eventItem.getExtraFields().get(i).getName().equals("EVENTTYPE")) {
holder.eventType.setVisibility(View.VISIBLE);
holder.eventType.setText(eventItem.getExtraFields().get(i).getValue().getValue());
}
}
holder.eventCategory.setText(eventItem.getCategories().get(0).getName());
return convertView;
}
private Date getDate(String date) {
String json = date;
String timeString = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
String[] timeSegments = timeString.split("\\+");
// May have to handle negative timezones
int timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
long millis = Long.valueOf(timeSegments[0]);
time = new Date(millis + timeZoneOffSet);
return time;
}
static class RecordHolder {
TextView salary;
ImageView eventImage;
TextView eventTitle;
TextView eventTitleDescription;
TextView eventCountries;
TextView eventRegions;
TextView eventCategory;
TextView eventType;
TextView eventDate;
}
}
Have i done something wrong or it is an android visual bug ??
UPDATED:
event_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ebf5fb"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:visibility="gone"
android:id="#+id/event_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
<TextView
android:id="#+id/event_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#043c5b"
android:textStyle="bold"
android:singleLine="true"
android:textSize="17sp"
android:paddingBottom="10dp"/>
<TextView
android:id="#+id/event_title_description"
android:layout_width="wrap_content"
android:singleLine="true"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:id="#+id/event_countries"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:id="#+id/event_regions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:id="#+id/event_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:visibility="gone"
android:id="#+id/event_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:visibility="gone"
android:id="#+id/job_salary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"
android:text="#string/salary"/>
<TextView
android:visibility="gone"
android:id="#+id/event_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
</LinearLayout>
Got it ,Please update your null checking .
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder;
convertView = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.from(activity).inflate(R.layout.community_common_tab_layout, null);
holder.DashBoard_Tab_List_Root=(LinearLayout)convertView.findViewById(R.id.Community_Common_Root);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText( dataArray.get(position).countryName);
holder.language.setText( dataArray.get(position).language);
holder.Capital.setText( dataArray.get(position).capital);
return convertView;
}
public static class ViewHolder {
public LinearLayout DashBoard_Tab_List_Root;
public TextView Tv_Badge_View;
}
}

Categories

Resources