I have a ListView and custom adapter and trying to get my data to be displayed inside of the ListView. I have three layouts to show the data but not able to get the data to display. I am having the hardcoded text of GROCERY being populated in each row for the list view not the three layouts I want and their respected data.
CustomAdapter
public class CompleteEReceiptDisplay extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
Toolbar mToolbar;
private ImageView menuBtn, backBtn;
ListView mFullReceiptLV;
List<EreceiptPojo> mainList = new ArrayList<>();
private LayoutInflater mInflater;
private RelativeLayout mFullItemLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Show Toolbar without extending AppCompatActivity
delegate = AppCompatDelegate.create(this, this);
delegate.onCreate(savedInstanceState);
delegate.setContentView(R.layout.complete_ereceipt_display);
delegate.setSupportActionBar(mToolbar);
mFullReceiptLV = (ListView) findViewById(R.id.fullEReceiptListView);
menuBtn = (ImageView) findViewById(R.id.menuBtn);
backBtn = (ImageView) findViewById(R.id.icnBackArrow);
menuBtn.setVisibility(View.GONE);
backBtn.setVisibility(View.VISIBLE);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
parseList();
FullEReceiptAdapter mFullAdapter = new FullEReceiptAdapter(this);
mFullReceiptLV.setAdapter(mFullAdapter);
}
private void parseList() {
String itemCateg = "", itemPrice = "", itemDesc = "";
HashMap<String, List<HashMap<String, String>>> mHashMap = new HashMap<>();
List<LineDetail> mLineDetailList = MainActivity.mCompleteReceiptData.getLineDetailList().getLineDetail();
for (int i = 0; i < mLineDetailList.size(); i++) {
LineDetail lineDetail = mLineDetailList.get(i);
itemPrice = lineDetail.getPrice();
List<Item> itemList = lineDetail.getCustomAttributes().getItem();
for (int j = 0; j < itemList.size(); j++) {
Item it = itemList.get(j);
if (it.getKey().equalsIgnoreCase("PrintCategory")) {
itemCateg = it.getValue();
} else if (it.getKey().equalsIgnoreCase("ItemDescription")) {
itemDesc = it.getValue();
}
}
HashMap<String, String> hm = new HashMap<>();
hm.put(itemDesc, itemPrice);
if (mHashMap.containsKey(itemCateg)) {
mHashMap.get(itemCateg).add(hm);
} else {
List<HashMap<String, String>> mMap = new ArrayList<>();
mMap.add(hm);
mHashMap.put(itemCateg, mMap);
}
}
for (Map.Entry<String, List<HashMap<String, String>>> entry : mHashMap.entrySet()) {
itemCateg = entry.getKey();
double mDouble = 0.00;
EreceiptPojo ereceiptPojo = new EreceiptPojo();
ereceiptPojo.setItemName(itemCateg);
ereceiptPojo.setCategory(true);
ereceiptPojo.setSubTotal(false);
mainList.add(ereceiptPojo);
List<HashMap<String, String>> dummyList = entry.getValue();
for (int i = 0; i < dummyList.size(); i++) {
HashMap<String, String> hm1 = new HashMap<>();
hm1 = dummyList.get(i);
for (Map.Entry<String, String> entry1 : hm1.entrySet()) {
EreceiptPojo ereceiptPojo1 = new EreceiptPojo();
ereceiptPojo.setItemName(entry1.getKey());
ereceiptPojo1.setItemPrice(entry1.getValue());
ereceiptPojo1.setCategory(false);
ereceiptPojo1.setSubTotal(false);
mainList.add(ereceiptPojo1);
mDouble = mDouble + Double.parseDouble(entry1.getValue());
}
}
EreceiptPojo mEreceiptPojo = new EreceiptPojo();
mEreceiptPojo.setItemPrice(String.valueOf(mDouble));
mEreceiptPojo.setCategory(false);
mEreceiptPojo.setSubTotal(true);
mainList.add(mEreceiptPojo);
}
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
public class FullEReceiptAdapter extends BaseAdapter {
public static final int TYPE_ITEM = 0;
public static final int TYPE_CATEGORY = 1;
public static final int TYPE_ITEM_NAME = 2;
public static final int TYPE_PRICE = 3;
public FullEReceiptAdapter(Context context) {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mainList.size();
}
#Override
public Object getItem(int position) {
return mainList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EreceiptPojo obj = mainList.get(position);
ViewHolder holder = null;
int layout_type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.full_receipt_category_header, parent, false);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (obj.isCategory() == true) {
holder = new ViewHolder();
holder.mHeaderView = (LinearLayout) convertView.findViewById(R.id.full_receipt_category_header_layout);
}
if (obj.isSubTotal() == true) {
holder = new ViewHolder();
holder.mLineItemsTotalPrice = (LinearLayout) convertView.findViewById(R.id.subTotalView);
}
if(obj.getItemName().length() > 0 && obj.getItemPrice().length() > 0) {
holder = new ViewHolder();
holder.mLineItemName = (RelativeLayout) convertView.findViewById(R.id.full_receipt_item_line);
}
return convertView;
}
}
public static class ViewHolder {
public LinearLayout mHeaderView;
public TextView mLineItemName;
public TextView mLineItemPrice;
public LinearLayout mLineItemsTotalPrice;
}
}
Three layouts I am tryign to attach to the adapter.
The first layout is the one that keeps repeating within the ListView.
<?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:id="#+id/full_receipt_category_header_layout">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/full_receipt_category_header_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="15dp"
android:text="GROCERY"
android:textAllCaps="true"
android:textColor="#color/colorBlack"
android:textSize="22dp"
android:textStyle="bold" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtLineItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CUB SPLT TOP WHEAT"
android:textSize="16sp"/>
<TextView
android:id="#+id/txtLineItemPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="$1.70*"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<?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:id="#+id/subTotalView">
<View
android:layout_width="50dp"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:background="#color/colorGrey"
android:layout_gravity="right"/>
<TextView
android:id="#+id/txtCategoryTotalPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:text="$5.70"
android:textColor="#color/colorBlack"
android:layout_gravity="right"/>
</LinearLayout>
The layout that contains the ListView
<?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">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_receipt"
android:padding="10dp">
<ImageView
android:id="#+id/bannerReceiptLogo"
android:layout_width="170dp"
android:layout_height="75dp"
android:background="#drawable/img_logo_receipt_cub"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"/>
<TextView
android:id="#+id/bannerAddressHeader"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="#string/storeHeader"
android:layout_below="#id/bannerReceiptLogo"
android:layout_marginTop="10dp"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:textSize="18sp"/>
<ListView
android:id="#+id/fullEReceiptListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bannerAddressHeader"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp">
</ListView>
</RelativeLayout>
</LinearLayout>
I was able to get this working as I had to inflate each layout inside my adapter for each position within the view. The chances are in the getView().
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EreceiptPojo obj = mainList.get(position);
TaxDetail taxDetail = new TaxDetail();
ViewHolder holder = null;
if (obj.isCategory()) {
convertView = mInflater.inflate(R.layout.full_receipt_category_header, parent, false);
TextView mCat = (TextView) convertView.findViewById(R.id.full_receipt_category_header_text);
mCat.setText(obj.getItemName());
}
else if (obj.isSubTotal()) {
convertView = mInflater.inflate(R.layout.full_receipt_category_total, parent, false);
TextView subTotal = (TextView) convertView.findViewById(R.id.txtCategoryTotalPrice);
subTotal.setText(obj.getItemPrice());
}
else if(!obj.isSubTotal() && !obj.isCategory()){
convertView = mInflater.inflate(R.layout.full_receipt_item_line, parent, false);
TextView itemName = (TextView) convertView.findViewById(R.id.txtLineItem);
TextView itemPrice = (TextView) convertView.findViewById(R.id.txtLineItemPrice);
itemName.setText(obj.getItemName());
itemPrice.setText(obj.getItemPrice());
} else {
convertView = mInflater.inflate(R.layout.tax_layout, parent, false);
TextView mFinalSubtotal = (TextView) convertView.findViewById(R.id.txtSubTotalFinal);
TextView mTotalTax = (TextView) convertView.findViewById(R.id.txtTaxTotal);
TextView mPurchaseTotal = (TextView) convertView.findViewById(R.id.txtCompleteTotalNumber);
for(int i = 0; i < obj.getItemPrice().length(); i++) {
String subTotalFinal = obj.setItemPrice(i);
}
Related
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());
}
}
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.
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;
}
}
I have a layout which consist of a ListView and a TextView.
On the ListView items, it has one Button. On the Button's onClickListener, is it able to change the text of the TextView that is on the parent layout?
I have set the Button's onClickListener but have not been able to find a way to let the Button change the TextView properties etc.
Thanks! :)
Layout:
// try this way,hope this will help you..
**XML** code
**activity**
<?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:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/txtChnageTextColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Android Demo Text For TextView"/>
<ListView
android:id="#+id/lstChangeTextColor"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"/>
</LinearLayout>
**list_item**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/txtColor"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="16sp"/>
<Button
android:id="#+id/btnSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"/>
</LinearLayout>
**ACTIVITY** code
**MyActivity**
public class MyActivity extends Activity{
private ListView lstChangeTextColor;
private TextView txtChnageTextColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
lstChangeTextColor = (ListView) findViewById(R.id.lstChangeTextColor);
txtChnageTextColor = (TextView) findViewById(R.id.txtChnageTextColor);
ArrayList<HashMap<String,String>> listItem = new ArrayList<HashMap<String,String>>();
HashMap<String,String> map1 = new HashMap<String, String>();
map1.put("name", "Red");
map1.put("value", "#FF0000");
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("name", "Orange");
map2.put("value", "#FFA500");
HashMap<String,String> map3 = new HashMap<String, String>();
map3.put("name", "Yellow");
map3.put("value", "#FFFF00");
HashMap<String,String> map4 = new HashMap<String, String>();
map4.put("name", "Lime");
map4.put("value", "#00FF00");
HashMap<String,String> map5 = new HashMap<String, String>();
map5.put("name", "Blue");
map5.put("value", "#0000FF");
listItem.add(map1);
listItem.add(map2);
listItem.add(map3);
listItem.add(map4);
listItem.add(map5);
lstChangeTextColor.setAdapter(new ListAdapter(this,listItem));
}
class ListAdapter extends BaseAdapter{
private ArrayList<HashMap<String,String>> listItem;
private Context context;
public ListAdapter (Context context,ArrayList<HashMap<String,String>> listItem) {
this.listItem = listItem;
this.context = context;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return listItem.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item,null,false);
holder.txtColor = (TextView) convertView.findViewById(R.id.txtColor);
holder.btnSet = (Button) convertView.findViewById(R.id.btnSet);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtColor.setText(listItem.get(position).get("name"));
holder.btnSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(new Runnable() {
#Override
public void run() {
txtChnageTextColor.setTextColor(Color.parseColor(listItem.get(position).get("value")));
}
});
}
});
return convertView;
}
}
class ViewHolder{
Button btnSet;
TextView txtColor;
}
}
As the title states, I'm having some troubles getting my custom listview adapter to work properly. The app displays nothing on the list, and gives just a blank white screen. I tested my data with a simple list I already have setup, and that worked just fine.
History.java
public class History {
public String score;
public String gametype;
public int icon;
public History() {
super();
}
public History(String score, String gametype, int icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:background="#111111">
</ListView>
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
I think you should replace ArrayAdapter by BaseAdapter and implement all required method e.g. getItemId(), getItem(), getCount(), getView().
It should work fine!.
Below is example code of mine, dont care about what is MusicModel.
protected class MusicCustomAdapter extends BaseAdapter {
private Activity context;
private List<MusicModel> musicModelList;
private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
public MusicCustomAdapter(Activity context, List<MusicModel> musicModelList) {
this.context = context;
this.musicModelList = musicModelList;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public Object getItem(int position) {
return this.musicModelList.get(position);
}
#Override
public int getCount() {
return this.musicModelList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = context.getLayoutInflater().inflate(R.layout.song_item, null);
}
MusicModel musicModel = (MusicModel) getItem(position);
TextView tvMusicName = (TextView) view.findViewById(R.id.tv_song_name);
tvMusicName.setText(musicModel.getName());
TextView tvArtist = (TextView) view.findViewById(R.id.tv_artist);
tvArtist.setText(musicModel.getArtist());
TextView tvDuration = (TextView) view.findViewById(R.id.tv_duration);
tvDuration.setText(sdf.format(musicModel.getDuration()));
ImageView imgThumbnail = (ImageView) view.findViewById(R.id.img_thumbnail);
imgThumbnail.setImageDrawable(musicModel.getThumbnail());
return view;
}
}
Hope this help.
You need to override getCount() in your custom adapter.
It will return the number of entries in your ListView.
#Override
public int getCount() {
return myArrayList.size();
}