I am having problems in displaying cards dynamically from a recycler view. Here's my code.
CardActivity.java
public class CardActivity extends AppCompatActivity {
CardAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<CardModel> data = new ArrayList<>();
public static String IMGS[] = {
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/12540788_486126334923939_641652950626105372_n.jpg?oh=520090fa887ded912ddb7086fc69fc93&oe=57A04969",
"https://scontent.fmnl4-2.fna.fbcdn.net/t31.0-8/12973436_521081094761796_6679453535369186441_o.jpg",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/12191632_465602330309673_5460380145671805117_n.jpg?oh=51811b46395fee6e4bdb5394e6725591&oe=57D35DC3",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/10628472_397420133794560_5446805358922772021_n.jpg?oh=f23ab8761e05b2a50d0d0c9dec4d365b&oe=57DBF1CC",
"https://scontent.fmnl4-2.fna.fbcdn.net/t31.0-8/10697227_314766035393304_2937143993369666506_o.jpg",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/13133194_10154674163886840_3764712620850385571_n.jpg?oh=252cedf88040188f12ce99c29f3dd47e&oe=57DD7474"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
for (int i = 0; i < IMGS.length; i++) {
CardModel cardModel = new CardModel();
cardModel.setTitle("Card Title: " + i);
cardModel.setDescription("This is a card description");
cardModel.setUrl(IMGS[i]);
data.add(cardModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Cards");
mRecyclerView = (RecyclerView) findViewById(R.id.cards);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CardActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
mAdapter = new CardAdapter(CardActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
}
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
}
CardModel.java
public class CardModel {
String url,title,description;
public CardModel() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardHolder> {
private LayoutInflater inflater;
Context context;
List<CardModel> data = new ArrayList<>();
public CardAdapter(Context context, List<CardModel> data){
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
#Override
public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_layout,parent,false);
CardHolder cardHolder = new CardHolder(view);
return cardHolder;
}
#Override
public void onBindViewHolder(CardHolder holder, int position) {
holder.cardTitle.setText(data.get(position).getTitle());
holder.cardDescription.setText(data.get(position).getDescription());
Glide.with(context).load(data.get(position).getUrl())
.fitCenter()
.into(holder.cardImage);
}
#Override
public int getItemCount() {
return 0;
}
public static class CardHolder extends RecyclerView.ViewHolder {
ImageView cardImage;
TextView cardTitle;
TextView cardDescription;
public CardHolder(View cardView) {
super(cardView);
cardImage = (ImageView) cardView.findViewById(R.id.card_image);
cardTitle = (TextView) cardView.findViewById(R.id.card_title);
cardDescription = (TextView) cardView.findViewById(R.id.card_description);
}
}
}
activity_card.xml
<FrameLayout 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="com.braudy.android.mesasixprofiler.CardActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/toolbar"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
card_layout.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:background="#FFFFFF"
android:padding="10dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#ffffff">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:alpha=".7"
android:id="#+id/card_image"
android:background="#ffff66"
android:src="#drawable/img1"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Braudy"
android:paddingLeft="15dp"
android:textColor="#FFFFFF"
android:background="#707070"
android:alpha=".8"
android:textSize="25sp"
android:id="#+id/card_title"
android:layout_alignBottom="#+id/card_image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="This is a description"
android:paddingTop="5dp"
android:paddingLeft="15dp"
android:textColor="#A9A9AF"
android:textSize="15sp"
android:id="#+id/card_description"
android:layout_below="#+id/card_image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Change this
#Override
public int getItemCount() {
return 0;
}
to
#Override
public int getItemCount() {
return data.size();
}
change here-
#Override
public int getItemCount() {
return data.size();
}
You have to declare how much views you want to inflate in your view.
Related
After some research on this one of the complex issue
I did this like this for my currency convertor project:
Below are steps:
Created A Custom Adapter with inner ViewHolder
Created an Interference for Selection changed and to notify the
Adaper in MainActivty
Created an Model Class Created an layout for My list
Coding:
Adapter and View Holder
class Adapter extends RecyclerView.Adapter<Adapter.VH> {
ArrayList<Currency> list, checkedCurrencies = new ArrayList<>();
CurrencySelectionChangelistener listener;
public Adapter(#NonNull ArrayList<Currency> list, CurrencySelectionChangelistener listener) {
this.list = list;
this.listener = listener;
}
#NonNull
#Override
public VH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new VH(LayoutInflater.from(getContext()).inflate(R.layout.layout_list_of_all_items, parent, false));
}
#Override
public void onBindViewHolder(#NonNull VH holder, #SuppressLint("RecyclerView") int position) {
Currency currentCurrency = list.get(position);
holder.checkBox.setChecked(currentCurrency.isChecked());
holder.mDis.setText(currentCurrency.getDescription());
//ignore below line it's just for sorting the string to set On TextView and with another purpose
String name = currentCurrency.getName().toLowerCase().replace(" ", "");
holder.mName.setText(name.toUpperCase());
holder.mLogo.setImageResource(currentCurrency.getLogo(name));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
list.get(position).setChecked(true);
checkedCurrencies.add(currentCurrency);
} else if (!holder.checkBox.isChecked()) {
list.get(position).setChecked(false);
checkedCurrencies.remove(currentCurrency);
}
//calling the interference's function
onSelection(checkedCurrencies);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class VH extends RecyclerView.ViewHolder {
TextView mName, mDis;
ImageView mLogo;
CheckBox checkBox;
public VH(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkboxAllItems);
mLogo = itemView.findViewById(R.id.ImageViewAllItemLogo);
mName = itemView.findViewById(R.id.textViewAllItemCName);
mDis = itemView.findViewById(R.id.textViewAllItemCDis);
}
}
}
Interface
public interface CurrencySelectionChangelistener {
public void onSelection(ArrayList<Currency> currencies);}
Fragment in Which I'm using RecyclerView
public class AddMoreCurrencyFragment extends Fragment implements CurrencySelectionChangelistener {
FragmentAddNewCurrencyBinding binding;
ArrayList<Currency> currencies;
Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentAddNewCurrencyBinding.inflate(inflater);
CurrencyContainerActivity.title.setVisibility(View.VISIBLE);
CurrencyContainerActivity.title.setText("Add Currency");
CurrencyContainerActivity.backBtn.setVisibility(View.VISIBLE);
currencies = new ArrayList<>();
for (Currency c : CurrencyContainerActivity.listOfCurrencies) {
currencies.add(new Currency(c.getName(), c.getDescription(), false));
}
adapter = new Adapter(currencies, this);
binding.recView.setAdapter(adapter);
binding.done.setOnClickListener(view -> {
});
return binding.getRoot();
}
#Override
public void onSelection(ArrayList<Currency> currencies) {
CurrencyContainerActivity.listToAdd.addAll(currencies);
Toast.makeText(getContext(), currencies.toString(), Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
xml layout for each item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#color/white"
android:orientation="vertical"
android:weightSum="3">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="59dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp"
android:weightSum="3">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.89"
app:cardCornerRadius="16dp">
<ImageView
android:id="#+id/ImageViewAllItemLogo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/flag" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/textViewAllItemCName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="19dp"
android:layout_weight=".75"
android:fontFamily="#font/poppins"
android:text="#string/pkr"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/textViewAllItemCDis"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_weight="0.47"
android:fontFamily="#font/poppins"
android:text="#string/pkr"
android:textAlignment="textStart"
android:textColor="#color/black"
android:textSize="13sp" />
<CheckBox
android:id="#+id/checkboxAllItems"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_weight="0.90"
android:background="#drawable/radio_selector"
android:button="#android:color/transparent" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#3F000000" />
</LinearLayout>
Model Class
public class Currency {
private String Name, Description;
private int logo;
boolean isChecked;
public Currency(String name, String description, boolean isChecked) {
Name = name;
Description = description;
this.isChecked = isChecked;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
if anything i missed can for that. Thanks
I have an AlertDialog in it there used to be a ListView in which the contents of the ArrayList were displayed. For beauty, I decided to replace it with Recyclerview, Card and the problems started.
Items are added to ArrayList <String> mainListWord during the work and they should be included in the Recyclerview cards. The problem is that either the entire list falls into one card at once, or each next card contains the previous elements + 1. For example: the first card: 1 element, the second card: 2 elements, etc.
How to implement it so that when a new element is added to the array, it will be placed in its own card?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<EditText
android:id="#+id/innerText"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Press"
android:layout_below="#id/innerText"
android:layout_centerHorizontal="true"
android:onClick="openDialog"/>
</RelativeLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_margin="4dp"
app:cardBackgroundColor="#color/colorCardBack">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/colorCard">
<ImageView
android:id="#+id/imageView_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="4dp" />
<TextView
android:id="#+id/textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text_1"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_centerInParent="true"
android:textSize="16sp"
android:layout_marginStart="5dp"
android:layout_toEndOf="#id/imageView_1"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
stats_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:layout_margin="10dp"
android:background="#color/colorAccent"
android:scrollbars="vertical"
android:layout_above="#id/butClose"/>
<Button
android:id="#+id/butClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText innerText;
private Button press, butClose;
private ArrayList<RecyclerViewItem> recyclerViewItem;
private ArrayList<String> mainListWord;
private AlertDialog OptionDialog;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewItem = new ArrayList<>();
mainListWord = new ArrayList<>();
innerText = findViewById(R.id.innerText);
press = findViewById(R.id.butClose);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void makeRecyclerList(ArrayList<String> income){
String[] listWord_lenght = income.toArray(new String[0]);
String keyWord = (String.join("", listWord_lenght));
recyclerViewItem.add(new RecyclerViewItem(R.drawable.star, keyWord));
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void openDialog(View v){
String word = innerText.getText().toString();
mainListWord.add(word);
makeRecyclerList(mainListWord);
Dialogus();
innerText.setText("");
}
public void Dialogus(){
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.stats_fragment, null, false);
OptionDialog = new AlertDialog.Builder(this).create();
OptionDialog.setTitle("TestInfo");
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(recyclerViewItem);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
butClose = v.findViewById(R.id.butClose);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
butClose.setBackgroundColor(Color.CYAN);
butClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OptionDialog.dismiss();
}
});
OptionDialog.show();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewViewHolder> {
private ArrayList<RecyclerViewItem> arrayList;
public static class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView_1;
public TextView textview_1;
public RecyclerViewViewHolder(#NonNull View itemView) {
super(itemView);
imageView_1 = itemView.findViewById(R.id.imageView_1);
textview_1 = itemView.findViewById(R.id.textview_1);
}
}
public RecyclerViewAdapter(ArrayList<RecyclerViewItem> arrayList){
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
RecyclerViewViewHolder recyclerViewViewHolder= new RecyclerViewViewHolder(view);
return recyclerViewViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewViewHolder recyclerViewViewHolder, int position) {
RecyclerViewItem recyclerViewItem = arrayList.get(position);
recyclerViewViewHolder.imageView_1.setImageResource(recyclerViewItem.getImageResource());
recyclerViewViewHolder.textview_1.setText(recyclerViewItem.getText_1());
}
#Override
public int getItemCount() {
return arrayList.size();
}
}
RecyclerViewItem.java
package freijer.app.one;
public class RecyclerViewItem {
private int imageResource;
private String text_1;
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
public String getText_1() {
return text_1;
}
public void setText_1(String text_1) {
this.text_1 = text_1;
}
public RecyclerViewItem(int imageResource, String text_1) {
this.imageResource = imageResource;
this.text_1 = text_1;
}
}
I followed this code on SearchView In ListView having a custom Adapter
which works fine.I tried to implement it on my project but seems to be not working.
provided that data is populated from Firebase database server.
I have removed the code for firebase which is not cause of the error.
I don't get any error but it is not working.
Here is what I have tried :
ShowFriendsActivity.java
public class ShowFriendsActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
private ListView mMessageListView;
private ShowFriendsAdapter showFriendsAdapter;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_online_users);
searchView = (SearchView) findViewById(R.id.myownsearchview);
SettingFirebaseAndListView();
}
private void SettingFirebaseAndListView() {
mMessageListView = (ListView) findViewById(R.id.show_friends_listview);
final List<AuthenticatedUser> authenticatedUserList = new ArrayList<>();
showFriendsAdapter = new ShowFriendsAdapter(this, R.layout.show_friends_item_layout, authenticatedUserList);
mMessageListView.setAdapter(showFriendsAdapter);
mMessageListView.setTextFilterEnabled(true);
setupSearchView();
}
private void setupSearchView() {
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setSubmitButtonEnabled(true);
searchView.setQueryHint("Search Friend");
}
#Override
public boolean onQueryTextSubmit(String newText) {
return true;
}
#Override
public boolean onQueryTextChange(String s) {
mMessageListView.setFilterText(s);
return false;
}
}
ShowFriendsAdapter.java CustomAdapter which extends ArrayAdapter and implements Filterable Interface
public class ShowFriendsAdapter extends ArrayAdapter<AuthenticatedUser> implements Filterable{
Cursor cr;
SQLiteDatabase db;
Context context;
List<AuthenticatedUser> listofAuthenticatedUsers;
List<AuthenticatedUser> listofAuthenticatedUsers2;
public ShowFriendsAdapter(Context context, int resource,List<AuthenticatedUser> objects) {
super(context, resource, objects);
this.context = context;
listofAuthenticatedUsers = objects;
}
public Filter getFilter(){
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<AuthenticatedUser> results = new ArrayList<AuthenticatedUser>();
if(listofAuthenticatedUsers2==null)
listofAuthenticatedUsers2=listofAuthenticatedUsers;
if(constraint!=null){
if (listofAuthenticatedUsers2 != null && listofAuthenticatedUsers2.size() > 0){
for (final AuthenticatedUser g : listofAuthenticatedUsers2) {
if (g.getName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#Override
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
listofAuthenticatedUsers = (ArrayList<AuthenticatedUser>) filterResults.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#NonNull
#Override
public View getView(int position,View convertView,ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.show_friends_item_layout, parent, false);
}
TextView userName = (TextView) convertView.findViewById(R.id.friend_name_textview);
TextView userEmail = (TextView) convertView.findViewById(R.id.friend_email_id_textview);
final ImageView userImage = (ImageView) convertView.findViewById(R.id.friend_name_image);
assert currentItem != null;
userName.setText(currentItem.getName());
userEmail.setText(currentItem.getEmail());
// If true , the app crashes
userImage.setClickable(true);
userImage.setEnabled(true);
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return convertView;
}
}
AuthenticatedUser.java
public class AuthenticatedUser {
private String Name;
private String Email;
private String imageUrl;
// constructor
public AuthenticatedUser(){}
public AuthenticatedUser(String name, String email, String imageUrl) {
Name = name;
Email = email;
this.imageUrl = imageUrl;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
The row layout show_friends_item_layout.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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/friend_name_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="8dp"
android:onClick="ChangeTheDisplayImage"
android:src="#drawable/contacts"
app:civ_border_color="#006064"
app:civ_border_width="2dp"
app:srcCompat="#drawable/contacts"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/friend_name_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name"
android:textColor="#color/black"
android:textSize="#dimen/authen_user_size"/>
<TextView
android:id="#+id/friend_email_id_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Email ID"
android:textColor="#color/black"
android:textSize="8sp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And my the main layout of my activity
show_online_users.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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="com.google.firebase.udacity.friendlychat.friends.ShowFriendsActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="60dp"
style="#style/HeaderBar"
app:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
app:popupTheme="#style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
android:elevation="4dp"
/>
<SearchView
android:id="#+id/myownsearchview"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/my_toolbar"
android:layout_marginTop="4dp"
android:tooltipText="Search"/>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefresh_Activity_show_Friends"
android:layout_marginTop="110dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:layout_marginTop="120dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/show_friends_listview"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
I am trying to implement a RecyclerView with two different layouts. In the MainActivity I first create ListItem object and add it to the list and then add that to the adapter, but it doesn't show. And also I am calling a method that creates ListItem object and adds it to the list and then notifies the adapter, but it still doesn't show. Here is my code so far:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
android:layout_height="match_parent"
tools:context="nl.iansoft.www.recyclerviewproblem.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp"
/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<ListItem> listItems;
private CustomAdapter customAdapter;
private RecyclerView rvList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvList = (RecyclerView)findViewById(R.id.rvList);
listItems = new ArrayList<>();
ListItem listItem = new ListItem("MyName", "MyLatsName", "MyEmail");
listItems.add(listItem);
customAdapter = new CustomAdapter(listItems);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
rvList.setLayoutManager(mLayoutManager);
rvList.setItemAnimator(new DefaultItemAnimator());
rvList.setAdapter(customAdapter);
addItemToTheList();
}
private void addItemToTheList(){
ListItem listItem = new ListItem("MyName", "MyLatsName", "MyEmail");
listItems.add(listItem);
customAdapter.notifyDataSetChanged();
}
}
CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ListItem> listItems;
public class ListItem1ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvLastName;
public TextView tvEmail;
public ListItem1ViewHolder(View view) {
super(view);
tvName = (TextView) view.findViewById(R.id.tvName);
tvLastName = (TextView) view.findViewById(R.id.tvLastName);
tvEmail = (TextView) view.findViewById(R.id.tvEmail);
}
}
public class ListItem2ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName2;
public TextView tvLastName2;
public TextView tvEmail2;
public ListItem2ViewHolder(View view) {
super(view);
tvName2 = (TextView) view.findViewById(R.id.tvName2);
tvLastName2 = (TextView) view.findViewById(R.id.tvLastName2);
tvEmail2 = (TextView) view.findViewById(R.id.tvEmail2);
}
}
public CustomAdapter(ArrayList<ListItem> listItems) {
this.listItems = listItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if(viewType == 1){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item, parent, false);
return new CustomAdapter.ListItem1ViewHolder(itemView);
}else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item2, parent, false);
return new CustomAdapter.ListItem2ViewHolder(itemView);
}
}
#Override
public int getItemViewType(int position) {
if(listItems.get(position).getName().equals("MyName")){
return 1;
}else{
return 2;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
if(holder.getItemViewType() == 1) {
ListItem1ViewHolder listItem1ViewHolder = (ListItem1ViewHolder) holder;
listItem1ViewHolder.tvName.setText(listItem.getName());
listItem1ViewHolder.tvLastName.setText(listItem.getLastName());
listItem1ViewHolder.tvEmail.setText(listItem.getEmail());
}else{
ListItem2ViewHolder listItem2ViewHolder = (ListItem2ViewHolder)holder;
listItem2ViewHolder.tvName2.setText(listItem.getName());
listItem2ViewHolder.tvLastName2.setText(listItem.getLastName());
listItem2ViewHolder.tvEmail2.setText(listItem.getEmail());
}
}
#Override
public int getItemCount() {
return listItems.size();
}
}
ListItem.java
public class ListItem {
private String name;
private String lastName;
private String email;
public ListItem() {
}
public ListItem(String name, String lastName, String email) {
this.name = name;
this.lastName = lastName;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my_list_item2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="Name2"
android:layout_marginTop="15dp"
android:padding="5dp"/>
<TextView
android:id="#+id/tvLastName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Last Name2"
android:layout_below="#+id/tvName2"
android:layout_marginTop="10dp"
android:padding="5dp" />
<TextView
android:id="#+id/tvEmail2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="my#email.com"
android:layout_below="#+id/tvLastName2"
android:layout_marginTop="5dp"
android:padding="5dp" />
</RelativeLayout>
my_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="Name"
android:layout_marginTop="15dp"
android:padding="5dp"/>
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Last Name"
android:layout_below="#+id/tvName"
android:layout_marginTop="10dp"
android:padding="5dp" />
<TextView
android:id="#+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="my#email.com"
android:layout_below="#+id/tvLastName"
android:layout_marginTop="5dp"
android:padding="5dp" />
</RelativeLayout>
The issue is in ConstraintLayout. Because you haven't specified any constraints to your RecyclerView.
Either specify constraints, or move to another layout (e.g. FrameLayout).
But specifically in this case you do not need parent layout, because it is useless, as long as you have only RecyclerView in your view hierarchy.
i want to be able to do this to the code i have already I am new to programing please help.
- Add an icon the user can click (per item) to remove it
- When clicked that item on the list should be removed
-The item should be removed from storage as well (so it doesn't appear next time they load up the app)
here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String Log_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox CheckBox = (CheckBox) convertView.findViewById(R.id.CheckBox);
textView.setText(items.get(position).getDescription());
CheckBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
todolistmanager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if(json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit = savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
todoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return getDescription();
}
}
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/hintTxtItem"
/>
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/lblBtnAdd"
android:layout_toRightOf="#id/txtItem"
/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:text="#string/txtEmpty"
android:gravity="center_horizontal"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:choiceMode="multipleChoice" >
</ListView>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
to_do_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<CheckBox
android:id="#+id/CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<ListView
android:layout_weight="20"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
Step1: Create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/txtItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text" />
<Button
android:id="#+id/btnAdd"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txtItem"
android:text="Add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/lvTodo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice" />
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:text="No data"
android:visibility="invisible" />
</RelativeLayout>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Step2: Create to todo_item.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:gravity="center"
android:padding="10dp"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/tvTodoName"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Learn Android"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cbChooseTodo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Step3: Define Object Todo
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description, boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isComplete() {
return isComplete;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
}
Step4: Create TodoItemAdapter class
public class TodoItemAdapter extends ArrayAdapter<ToDoItem> {
private ArrayList<ToDoItem> arrayListTodo;
private LayoutInflater layoutInflater;
public TodoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) {
super(context, resource, objects);
this.arrayListTodo = objects;
this.layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.todo_item, parent,false);
holder.tvTodoName = (TextView)convertView.findViewById(R.id.tvTodoName);
holder.cbTodoChoose = (CheckBox)convertView.findViewById(R.id.cbChooseTodo);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
final ToDoItem toDoItem = arrayListTodo.get(position);
holder.tvTodoName.setText(toDoItem.getDescription());
holder.cbTodoChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toDoItem.setComplete(isChecked);
}
});
holder.cbTodoChoose.setChecked(toDoItem.isComplete());
return convertView;
}
public static class ViewHolder{
public TextView tvTodoName;
public CheckBox cbTodoChoose;
}
}
Step5: Process on the MainActivity class
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ListView lvTodoItem;
private ArrayList<ToDoItem> toDoItems;
private TodoItemAdapter todoItemAdapter;
private Button btnDel;
private Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData(){
toDoItems = new ArrayList<>();
todoItemAdapter = new TodoItemAdapter(MainActivity.this, R.layout.todo_item, toDoItems);
lvTodoItem = (ListView)findViewById(R.id.lvTodo);
lvTodoItem.setAdapter(todoItemAdapter);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnDel = (Button)findViewById(R.id.btnDel);
btnAdd.setOnClickListener(this);
btnDel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnAdd:
addTodoItem();
break;
case R.id.btnDel:
deleteTodoItem();
break;
}
}
private void addTodoItem() {
}
private void deleteTodoItem() {
for (int i= toDoItems.size()-1; i>=0 ; i--){
ToDoItem toDoItem = toDoItems.get(i);
if (toDoItem.isComplete()){
toDoItems.remove(i);
}
}
todoItemAdapter.notifyDataSetChanged();
}
}
It is working fine. Thanks.