RecyclerView Displays only last objects in List - android

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.

Related

RecyclerView shows Strings but not Images

I have a SQLite database and want to search Items thorugh DB and then showing the items on recyclerView. Everything looking fine but recyclerView not showing the pictures, But somehow It shows the Strings
Normally pictures I saved inside the SQLite as BLOB should be displayed on the left.
Here is SearchFragment (Where I make the search and start recyclerView to display items)
public class SearchFragment extends Fragment {
Button searchbutton;
EditText editText;
View v;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_search, container, false);
addListenerOnButton(v);
return v;
}
private void addListenerOnButton(View v) {
searchbutton = v.findViewById(R.id.searchfragment_button);
editText = v.findViewById(R.id.searchfragment_edittext);
searchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String keystring = editText.getText().toString();
if(keystring.isEmpty())
Toast.makeText(getContext(),R.string.empty_search ,Toast.LENGTH_LONG).show();
else
new FoodQuery().execute(keystring);
}
});
}
//Place I start the search on background
private class FoodQuery extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String [] keys) {
String name_col;
DietAppDatabaseHelper daDBHelper;
SQLiteDatabase daDB;
daDBHelper = new DietAppDatabaseHelper(getContext());
try {
daDB = daDBHelper.getReadableDatabase();
if (Locale.getDefault().getLanguage() == "tr")
name_col = "name_tr";
else
name_col = "name_eng";
String query = "SELECT * FROM food_data WHERE " //Query here
+ name_col + " LIKE ?" ;
cursor = daDB.rawQuery(query, new String[]{"%" + keys[0] + "%"});
viewResults(name_col);
daDB.close();
} catch (SQLiteException e){
Log.d("SearchFragment", "doInBackground: " + e);
}
return null;
}
}
private void viewResults(String lang) {
int name_col = -1; //For language issues not important
if(lang == "name_tr")
name_col = 1;
else if(lang == "name_eng")
name_col = 2;
ArrayList<String> tmpnames = new ArrayList<>(); //I put pictures to byte[] and names to String Arraylist here
ArrayList<byte[]> tmppictures = new ArrayList<>();
if(cursor.moveToFirst()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
while(cursor.moveToNext()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
}
}
else {
Looper.prepare();
Toast.makeText(getContext(), R.string.no_food_found, Toast.LENGTH_LONG).show(); //To prevent empty search
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
RecyclerView recyclerView = v.findViewById(R.id.recycler_view);
SearchResultAdapter adapter = new SearchResultAdapter(getContext(), tmppictures, tmpnames);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);
}
});
}
}
Layout File of SearchFragment
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.SearchFragment"
android:id="#+id/fragment_search">
<Button
android:id="#+id/searchfragment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="#string/nav_search"
android:textColor="#FFFFFF"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:id="#+id/searchfragment_edittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="64dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="#+id/searchfragment_button"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="124dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the adapter
public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder>{
private ArrayList<byte[]> foodimages;
private ArrayList<String> foodnames;
private Context context;
public SearchResultAdapter(Context context, ArrayList<byte[]> foodimages, ArrayList<String> foodnames) {
this.foodimages = new ArrayList<>(foodimages);
this.foodnames = new ArrayList<>(foodnames);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_result_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.foodname.setText(foodnames.get(position));
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
}
#Override
public int getItemCount() {
return foodnames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView foodimage;
TextView foodname;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
foodimage = itemView.findViewById(R.id.food_seacrh_image);
foodname = itemView.findViewById(R.id.food_search_name);
parentLayout = itemView.findViewById(R.id.search_item);
}
}
}
Lastly, the layout of my item to use in recyclerView
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/search_item">
<ImageView
android:id="#+id/food_seacrh_image"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<TextView
android:id="#+id/food_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/food_seacrh_image"
android:textColor="#FFFFFF"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:textSize="17sp"
android:layout_toEndOf="#+id/food_seacrh_image"
android:layout_marginStart="30dp" />
It seems like the problem could be the line:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
Should probably be:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.get(position).size));
The third param on decodeByteArray should be the length (in bytes) of the image, you are passing in the actual number of images.

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

Can't get ImageView to show up on RecyclerView

I am just learning the RecyclerView and cannot figure out why the imageView with android:id="#+id/im_item_icon" will not show up on the screen. I even have another imageView that works but when I swap the IDs the original not working view works and the working one will not work. So basically the problem must be with the ID but I cannot figure out why. BTW I got the code from a blog "http://wiseassblog.com/tutorials/2016/03/04/how-to-build-a-recyclerview/"
DerpAdapter.java
public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder> {
private List<ListItem> listData;
private LayoutInflater inflater;
public DerpAdapter(List<ListItem> listData, Context c){
inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public DerpAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent, false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
ListItem item = listData.get(position);
holder.title.setText(item.getTitle());
holder.icon.setImageResource(item.getImageResId());
}
#Override
public int getItemCount() {
return listData.size();
}
class DerpHolder extends RecyclerView.ViewHolder {
private TextView title;
private ImageView icon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
icon = (ImageView)itemView.findViewById(R.id.im_item_icon);
//We'll need the container later on, when we add an View.OnClickListener
container = itemView.findViewById(R.id.cont_item_root);
}
}
DerpData.java
public class DerpData {
private static final String[] titles = {"Nothingness cannot be defined",
"Time is like a river made up of the events which happen, and a violent stream; " +
"for as soon as a thing has been seen, it is carried away, and another comes" +
" in its place, and this will be carried away too,",
"But when I know that the glass is already broken, every minute with it is precious.",
"For me, it is far better to grasp the Universe as it really is than to persist in" +
" delusion, however satisfying and reassuring.",
"The seeker after the truth is not one who studies the writings of the ancients and," +
" following his natural disposition, puts his trust in them, but rather the" +
" one who suspects his faith in them and questions what he gathers from them," +
" the one who submits to argument and demonstration, and not to the " +
"sayings of a human being whose nature is fraught with all kinds " +
"of imperfection and deficiency.",
"You must take personal responsibility. You cannot change the circumstances, the" +
" seasons, or the wind, but you can change yourself. That is something you" +
" have charge of."
};
private static final String[] subTitles = {"Bruce Lee",
"Marcus Aurelius",
"Meng Tzu",
"Ajahn Chah",
"Carl Sagan",
"Alhazen",
"Jim Rohn"
};
private static final int icon = R.drawable.ic_tonality_black_36dp;
public static List <ListItem> getListData() {
List <ListItem> data = new ArrayList <>();
//Repeat process 4 times, so that we have enough data to demonstrate a scrollable
//RecyclerView
for (int x = 0; x < 4; x++) {
//create ListItem with dummy data, then add them to our List
for (int i = 0; i < titles.length; i++) {
ListItem item = new ListItem();
item.setTitle(titles[i]);
item.setSubTitle(subTitles[i]);
data.add(item);
}
}
return data;
}
ListItem.java
public class ListItem {
private int imageResId;
private String subTitle;
private String title;
private boolean favourite = false;
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public boolean isFavourite() {
return favourite;
}
public void setFavourite(boolean favourite) {
this.favourite = favourite;
}
public int getImageResId() {
return imageResId;
}
public void setImageResId(int imageResId) {
this.imageResId = imageResId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
ListActivity.java
public class ListActivity extends AppCompatActivity {
private RecyclerView recView;
private DerpAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recView = (RecyclerView)findViewById(R.id.rec_list);
//Check out GridLayoutManager and StaggeredGridLayoutManager for more options
recView.setLayoutManager(new LinearLayoutManager(this));
adapter = new DerpAdapter(DerpData.getListData(), this);
recView.setAdapter(adapter);
}
activity_detail.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="application.binarysoup.jsonpractice.ui.DetailActivity">
<TextView
android:id="#+id/lbl_quote_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium" />
<TextView
android:id="#+id/lbl_quote_attribution"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/lbl_quote_text"
android:fontFamily="sans-serif-light"
android:textStyle="italic" />
activity_list.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="application.binarysoup.jsonpractice.ui.ListActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/rec_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="72dp"
android:background="#drawable/background_state_drawable"
android:clickable="true"
>
<ImageView
android:id="#+id/im_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="16dp"
android:src="#drawable/ic_tonality_black_36dp" />
<TextView
android:id="#+id/lbl_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/im_item_icon"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Sois comme l'eau mon ami"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/lbl_item_sub_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lbl_item_text"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Mononc' J"
android:textSize="14sp" />
<ImageView
android:id="#+id/im_item_icon_secondary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="true"
android:padding="16dp"
android:src="#drawable/ic_star_border_black_24dp"
android:background="#drawable/background_state_drawable"
/>
Can't get ImageView to show up on RecyclerView
You have to initialize imageResId in order to appear it in the recyclerView
for (int i = 0; i < titles.length; i++) {
ListItem item = new ListItem();
item.setTitle(titles[i]);
item.setSubTitle(subTitles[i]);
//put the code to initialise the imageResId here
data.add(item);
}

Remove selected dynamic checked items from listview

Here, in a listview I have added a custom row in which Checkbox and EditText are there and with a add button I just add multiple views to my listview. Adding is working perfectly but when it comes to removing part the checked items are not removing and apart from that suppose I selected two items, then two items from last deleted. I don't know whats going on with my code please help me.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AdapterCustom customAdapter;
ArrayList<String> stringArrayList;
ListView listView;
ArrayList<Integer> listOfItemsToDelete;
AdapterCustom.ViewHolder item;
int POS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfItemsToDelete = new ArrayList<Integer>();
stringArrayList = new ArrayList<String>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
listView = (ListView) findViewById(R.id.list_item);
customAdapter = new AdapterCustom(MainActivity.this, R.layout.main, stringArrayList);
}
public void addItems(View v) {
stringArrayList.add("");
listView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
public void removeItems(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
} else {
Log.i("Delete Pos", POS + "");
if (!listOfItemsToDelete.equals("")) {
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
}
}
}
AdapterCustom.java
public class AdapterCustom extends ArrayAdapter<String> {
Context context;
ArrayList<String> stringArrayList;
ArrayList<Boolean> positionArray;
MainActivity activity;
public AdapterCustom(Context context, int resourceId, ArrayList<String> arrayList) {
super(context, resourceId, arrayList);
this.context = context;
this.stringArrayList = arrayList;
positionArray = new ArrayList<Boolean>(stringArrayList.size());
for (int i = 0; i < stringArrayList.size(); i++) {
positionArray.add(false);
}
activity = new MainActivity();
}
#Override
public int getCount() {
return stringArrayList.size();
}
#Override
public String getItem(int position) {
return stringArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
EditText ediText;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
item = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.main, null);
item.ediText = (EditText) convertView.findViewById(R.id.ediText);
item.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
item.checkBox.setTag(new Integer(position));
convertView.setTag(item);
final View finalConvertView1 = convertView;
item.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
int getPosition = (Integer) compoundButton.getTag();
POS = getPosition;
listOfItemsToDelete.add(POS);
Log.i("position after check", POS + "");
Log.i("position check array", listOfItemsToDelete + "");
}
}
});
} else {
item = (ViewHolder) convertView.getTag();
}
item.checkBox.setTag(position);
return convertView;
}
}
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="10">
<Button
android:id="#+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="addItems"
android:text="Add New Item" />
<Button
android:id="#+id/goBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="goItems"
android:text="Go to Item" />
</LinearLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:drawSelectorOnTop="false"
android:visibility="visible" />
<Button
android:id="#+id/removeBtn"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:onClick="removeItems"
android:text="Remove Item" />
</LinearLayout>
main.xml
<LinearLayout
android:id="#+id/custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="10">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:id="#+id/ediText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#android:color/white"
android:hint="Type Anything You Want" />
</LinearLayout>
You only remove the item from the array. Try removing the item also from the list view adapter with adapter.remove(itemPosition);
What does mean
- j
in this code:
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
?
I think that:
for (String itemToRemove:listOfItemsToDelete) {
stringArrayList.remove(itemToRemove);
}
customAdapter.notifyDataSetChanged();
listOfItemsToDelete.clear();
would be appropriate.

Having troubles adding 3 layouts to 1 listview

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

Categories

Resources