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.
Related
When I add an item by button Scan Now, the public double sumCost value incrementes by the cost value in the AddItem method and then TextView(android:id="#+id/SumText") assigns this value. And How to decrease sumCost by the number that is in cost and set new text in TextView when pressing the Delete button? Thanks for any help
enter image description here
My full code:
MainActivity:
package com.example.testfirst;
...
public class MainActivity extends AppCompatActivity {
TextView sumText;
Button buttonAdd;
List<Contact> contacts = new LinkedList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
buttonAdd = (Button) findViewById(R.id.scanBtn);
sumText = (TextView) findViewById(R.id.SumText);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddItem("Tom", 2.45);
sumText.setText(Double.toString(sumCost));
}
});
}
public void AddItem(String name, double cost){
sumCost += cost;
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
contacts.add(new Contact(name,Double.toString(cost)));
}
public double sumCost = 0;
}
Contact(Model class):
...
public class Contact {
private String mName;
private String mCost;
public Contact(String name, String cost) {
mName = name;
mCost = cost;
}
public String getName() {
return mName;
}
public String getCost() {
return mCost;
}
}
ContactsAdapter:
...
public class ContactsAdapter extends RecyclerView.Adapter<ViewHolder>{
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_contact, parent, false);
return new ViewHolder(contactView).linkAdapter(this);
}
///////////////
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Contact contact = mContacts.get(position);
TextView textViewId = holder.nameId;
textViewId.setText(contact.getName());
TextView textViewCost = holder.nameCost;
textViewCost.setText(contact.getCost());
}
#Override
public int getItemCount() {
return mContacts.size();
}
List<Contact> mContacts;
public ContactsAdapter(List<Contact> contacts) {
mContacts = contacts;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private ContactsAdapter adapter;
public TextView nameId;
public TextView nameCost;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameId = (TextView) itemView.findViewById(R.id.text);
nameCost = (TextView) itemView.findViewById(R.id.textCost);
itemView.findViewById(R.id.delete).setOnClickListener(view -> {
adapter.mContacts.remove(getAdapterPosition());
adapter.notifyItemRemoved(getAdapterPosition());
});
}
public ViewHolder linkAdapter(ContactsAdapter adapter){
this.adapter = adapter;
return this;
}
}
item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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:layout_margin="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
app:contentPadding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/app_name"
android:textSize="20sp" />
<TextView
android:id="#+id/textCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:text="#string/app_name"
android:textSize="20sp" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:text="Delete" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
activity_users.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout 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=".MainActivity"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/SumText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="0.00"
android:textSize="30sp"/>
<Button
android:id="#+id/scanBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan now"
android:textSize="30sp"
android:layout_gravity="center_horizontal"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
One easy way to do that would be do add a "Decrementer" interface in the adapter that it can call to decrement the total cost, like this:
// Define the interface
public interface Decrementer {
void onDelete(double cost);
}
// Define an instance of the interface to hold
private final Decrementer mDecrementer;
// Pass in a decrementer at construction
public ContactsAdapter(List<Contact> contacts, Decrementer decr) {
mContacts = contacts;
mDecrementer = decr;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// get views and such ...
// Call the decrementer method when the button is clicked
// Could set this in onBindViewHolder, or pass the decrementer
// into the ViewHolder itself and use it there.
deleteButton.setOnClickListener(view -> {
int pos = holder.getAdapterPosition();
Contact c = mContacts.get(pos);
// add getCostAmount to return a double, or better yet, just
// store it as a Double instead of a string in Contact
mDecrementer.onDelete(c.getCostAmount());
mContacts.remove(pos);
notifyItemRemoved(pos);
});
}
and you would define the Decrementer when you create the adapter so it can access the Activity class members, like this:
ContactsAdapter adapter = new ContactsAdapter(contacts, new ContactsAdapter.Decrementer() {
#Override
public void onDelete(double cost) {
sumCost -= cost;
// change activity TextViews and such here too
sumText.setText(Double.toString(sumCost));
}
});
Side note: you don't need to create a whole new adapter every time you add an item, just add it to the contacts array and call an appropriate notifyDataSetChanged method on the existing adapter.
private ContactsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
//...
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
public void AddItem(String name, double cost){
sumCost += cost;
contacts.add(new Contact(name,Double.toString(cost)));
adapter.notifyDataSetChanged(); // or a less expensive notify call
}
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'm trying to show the data i got from the firebase in a listview. But my textview in listview doesn't change. This output i have two document my database. Two listview appear but can't change text.Where am i wrong?
OUTPUT
Here's my CustomAdapter code
public class MissionsAdapter extends ArrayAdapter<Missions> {
public MissionsAdapter(Context context, List<Missions> object){
super(context,0, object);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.item_missions,parent,false);
}
Missions mission = getItem(position);
TextView titleTextView = (TextView) convertView.findViewById(R.id.mission_title);
TextView expTextView = (TextView) convertView.findViewById(R.id.mission_exp);
TextView dateTextView = (TextView) convertView.findViewById(R.id.mission_date);
TextView descriptionTextView = (TextView) convertView.findViewById(R.id.mission_description);
TextView bilgitext=(TextView) convertView.findViewById(R.id.mission_bilgi);
titleTextView.setText(mission.getTitle());
expTextView.setText(mission.getExp());
dateTextView.setText(mission.getDate());
descriptionTextView.setText(mission.getDescription());
bilgitext.setText(mission.getBilgi());
return convertView;
}
}
Missions.java
public class Missions {
public String title;
public String exp;
public String date;
public String description;
public String bilgi;
public Missions() {}
public Missions(String title, String exp, String date, String description, String bilgi) {
this.title = title;
this.exp = exp;
this.date = date;
this.description = description;
this.bilgi=bilgi;
}
public String getTitle(){
return title;
}
public String getExp(){
return exp;
}
public String getDate(){
return date;
}
public String getDescription(){
return description;
}
public String getBilgi(){
return bilgi;
}
}
item_missions.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<TextView
android:id="#+id/mission_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textAppearance="?android:textAppearanceMedium"
android:hint="There will be a title"/>
<TextView
android:id="#+id/mission_exp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be exp"/>
<TextView
android:id="#+id/mission_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be a date"/>
<TextView
android:id="#+id/mission_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be a description"/>
<TextView
android:id="#+id/mission_bilgi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be a bilgi"/>
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/missionHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Edit/Create mission"
android:gravity="center"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textAllCaps="true"
android:textSize="30dp"
android:paddingTop="20dp"
/>
<ListView
android:id="#+id/missionList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
And finally MainActivity
public class MainActivity5 extends AppCompatActivity {
private final String COLLECTION_KEY = "İlanlar";
private TextView mHeaderView;
private ListView mMissionListView;
private FirebaseFirestore db;
private MissionsAdapter mMissionAdapter;
private ArrayList<Missions> mMissionsList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
mHeaderView = (TextView) findViewById(R.id.missionHeader);
mMissionListView = (ListView) findViewById(R.id.missionList);
mHeaderView.setText("Available Missions");
db = FirebaseFirestore.getInstance();
mMissionsList = new ArrayList<Missions>();
mMissionAdapter = new MissionsAdapter(MainActivity5.this, mMissionsList);
mMissionListView.setAdapter(mMissionAdapter);
db.collection(COLLECTION_KEY).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
List<Missions> mMissionsList = new ArrayList<>();
if(task.isSuccessful()){
for(QueryDocumentSnapshot document : task.getResult()) {
Missions miss = document.toObject(Missions.class);
mMissionsList.add(miss);
}
ListView mMissionsListView = (ListView) findViewById(R.id.missionList);
MissionsAdapter mMissionAdapter = new MissionsAdapter(MainActivity5.this, mMissionsList);
mMissionsListView.setAdapter(mMissionAdapter);
} else {
Log.d("MissionActivity", "Error getting documents: ", task.getException());
}
}
});
mMissionAdapter.addAll(mMissionsList);
}
}
Code
public class UsageSettings2 extends Fragment {
MainData mDatabaseHelper;
RecyclerView mRecyclerView;
UserDataHelper mHelper;
private List<UsageHelper> usage = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private UsageAdapter mAdapter;
SQLiteDatabase db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.settings_usage2, container, false);
final MainData myDBHlpr = new MainData(getActivity());
db = myDBHlpr.getWritableDatabase();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.usagelist);
//Add the data first
linearLayoutManager = new LinearLayoutManager(getActivity());
//and then create a object and pass the lis
mAdapter = new UsageAdapter(usage);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
Cursor csr = myDBHlpr.getAllQuestions2(getActivity());
while (csr.moveToNext()) {
String name = csr.getString(csr.getColumnIndex("Name"));
int sent = csr.getInt(csr.getColumnIndex("MessagesSent"));
int recieved = csr.getInt(csr.getColumnIndex("MessagesRecieved"));
int total = csr.getInt(csr.getColumnIndex("Messages"));
String time = csr.getString(csr.getColumnIndex("TimeSpent"));
new UsageHelper(name,sent,recieved,total,time);
int profile_counts = myDBHlpr.getProfilesCount2();
Log.d("FFF", String.valueOf(profile_counts));
}
return rootView;
}
}
Adapter
public class UsageAdapter extends RecyclerView.Adapter<UsageAdapter.UsageViewHolder>{
private List<UsageHelper> mUsageHelper;
public UsageAdapter(List<UsageHelper> UsageAdapter) {
this.mUsageHelper = UsageAdapter;
}
public class UsageViewHolder extends RecyclerView.ViewHolder{
public TextView mName;
public TextView mSent;
public TextView mRecieved;
public TextView mTotal;
public TextView mTime;
public UsageViewHolder(View view) {
super(view);
mName = (TextView)view.findViewById(R.id.name);
mSent = (TextView)view.findViewById(R.id.sent);
mRecieved = (TextView)view.findViewById(R.id.recieved);
mTotal = (TextView)view.findViewById(R.id.total);
mTime = (TextView)view.findViewById(R.id.time);
}
}
#Override
public UsageAdapter.UsageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_usage,parent,false);
return new UsageAdapter.UsageViewHolder(V);
}
#Override
public void onBindViewHolder(final UsageViewHolder holder, int position) {
final UsageHelper usageHelper = mUsageHelper.get(position);
holder.mName.setText(usageHelper.getName());
holder.mSent.setText(usageHelper.getSent());
holder.mRecieved.setText(usageHelper.getRecieved());
holder.mTotal.setText(usageHelper.getTotal());
holder.mTime.setText(usageHelper.getTime());
}
#Override
public int getItemCount() {
return mUsageHelper.size();
}
Modal
public class UsageHelper {
private String Name;
private int Sent;
private int Recieved;
private int Total;
private String Time;
public UsageHelper() {
}
public UsageHelper(String Name, int Sent ,int Recieved, int Total, String Time) {
this.Name = Name;
this.Sent = Sent;
this.Recieved = Recieved;
this.Total = Total;
this.Time = Time;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public int getSent() {
return Sent;
}
public void setSent(int sent) {
this.Sent = sent;
}
public int getRecieved() {
return Recieved;
}
public void setRecieved(int recieved) {
this.Recieved = recieved;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
this.Time = time;
}
public int getTotal() {
return Total;
}
public void setTotal(int total) {
this.Total = total;
}
}
The problem is that its not showing anything... the fragment is blank when i open it although the data is present... Any idea why its now showing any data? Im not getting any error just that the data isnt showing..........................................................................
Got an error after making changes according to answers
Custom
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/usage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black">
<RelativeLayout
android:weightSum="1"
android:id="#+id/linear"
android:padding="1dp"
android:background="#color/white"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15dp"
android:layout_toLeftOf="#+id/mid"
android:text="Name"
android:layout_alignParentStart="true"
android:id="#+id/name"
android:paddingVertical="10dp"
android:background="#color/black"
android:gravity="center_horizontal"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sent"
android:layout_toRightOf="#id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Sent"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/recieved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/sent"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Recieved"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/recieved"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Total"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/recieved"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Time \nSpent"
android:textColor="#color/white"
android:textSize="15dp" />
</RelativeLayout>
The usage list is always empty because you are not adding the new "UsageHelper" you are creating from your Cursor into the list.
What you need to do is the following:
Cursor csr = myDBHlpr.getAllQuestions2(getActivity());
while (csr.moveToNext()) {
...
UsageHelper newListItem = new UsageHelper(name,sent,recieved,total,time);
usage.add(newListItem);
...
}
mAdapter.notifyDataSetChanged();
When you finish adding elements to the list, you want to notify your adapter that the list has new items, so you have to call to mAdapter.notifyDataSetChanged(); and the new elements will be displayed
add mAdapter.notifyDataSetChanged(); in while condition or after adding your data in model class.
In the while loop of onCreateView(), add each row from the db to the list:
usage.add(new UsageHelper(name,sent,recieved,total,time));
instead of just:
new UsageHelper(name,sent,recieved,total,time)
which does nothing.
And after the loop finishes:
mAdapter.notifyDataSetChanged();
so the RecyclerView loads all the added rows to the list.
Edit
Replace
holder.mSent.setText(usageHelper.getSent());
with
holder.mSent.setText("" + usageHelper.getSent());
because usageHelper.getSent() is int and it is treated as a resource id.
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.