How to add a recycler view to fragment - java

I have tried many ways to add recyclerview inside a fragment. I'm new for android. My android have 5 fragments one of these fragment I need to add a recyclerview. here is my code
notification_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notification_item_root"
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical|left"
android:orientation="horizontal"
android:paddingLeft="16dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/notification_item_img"
android:layout_width="36dp"
android:layout_height="36dp"
android:src="#android:drawable/ic_input_get" />
<TextView
android:id="#+id/notification_item_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:paddingLeft="8dp"
android:text="Test Testre" />
</LinearLayout>
notification_Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.app.AlertController.RecycleListView
android:id="#+id/notification_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
NotificationItem.java
public class NotificationItem {
private String title;
private int imageResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageResId() {
return imageResId;
}
public void setImageResId(int imageResId) {
this.imageResId = imageResId;
}
}
NotificationData.java
public class NotificationData {
private static final String[] textItem = {"pathum", "sai", "charu"};
private static final int[] imgItem = {android.R.drawable.ic_popup_reminder, android.R.drawable.ic_menu_add, android.R.drawable.ic_menu_delete};
public static List<NotificationItem> getListData() {
List<NotificationItem> data = new ArrayList<>();
for (int x = 0; x < 4; x++) {
for (int i = 0; i < textItem.length && i < imgItem.length; i++) {
NotificationItem item = new NotificationItem();
item.setImageResId(imgItem[i]);
item.setTitle(textItem[i]);
data.add(item);
}
}
return data;
}
}
NotificationAdapter.java
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.NotificationHolder> {
private List<NotificationItem> listData;
private LayoutInflater inflater;
public NotificationAdapter(List<NotificationItem> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public NotificationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.notification_item,parent,false);
return new NotificationHolder(view);
}
#Override
public void onBindViewHolder(NotificationHolder holder, int position) {
NotificationItem item = listData.get(position);
holder.title.setText(item.getTitle());
holder.icon.setImageResource(item.getImageResId());
}
#Override
public int getItemCount() {
return listData.size();
}
class NotificationHolder extends RecyclerView.ViewHolder {
private TextView title;
private CircleImageView icon;
private View container;
public NotificationHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.notification_item_text);
icon = (CircleImageView) itemView.findViewById(R.id.notification_item_img);
container = itemView.findViewById(R.id.notification_item_root);
}
}
}
NotificationFragment.java
public class NotificationFragment extends Fragment {
RecyclerView recyclerView;
NotificationAdapter notificationAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.notification_fragment, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.notification_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
notificationAdapter = new NotificationAdapter(NotificationData.getListData(),this);
recyclerView.setAdapter(notificationAdapter);
return rootView;
}
}
I was unable to make it right in NotificationFragment.java and NotificationAdapter.java please help me guys.

You are using wrong class for RecyclerView, instead of AlertController.RecyclerListView use this:
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Here are some more informations:
RecyclerView

1) first add dependency to your app level gradle file then sync your project
compile 'com.android.support:recyclerview-v7:23.4.0'
2) go to your Layout file (eg: activity_main.xml) add recyclerview tag inside your base layout
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.examples.rehan.excluzo.Fragments.OneFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
3) create a class model.java and paste your code.
public class model{
private String name, gender;
public model() {
}
public model(String name, String gender) {
this.name= name;
this.gender= gender;
}
public String getGender() {
return gender;
}
public void setGender(String gneder) {
this.gender= gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
}
4)create xml file in your layout folder item_layout.xml and paste this code
<?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="match_parent"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp" >
<TextView
android:id="#+id/name"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/gender"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
5)your need to create adapter to add child views to your listview. so create a file testAdapter.java file and paste this code.
here in list view i will be having only 2 items(eg : Name and gender)
public class testAdapter extends RecyclerView.Adapter<testAdapter.MyViewHolder> {
private List<model> productList;
Context context;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
model product = productList.get(position);
holder.name.setText(product.getName());
holder.gender.setText(product.getGender());
}
#Override
public int getItemCount() {
return productList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,gender;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
gender = (TextView) view.findViewById(R.id.gender);
}
}
public testAdapter(List<model> productList, Context context) {
this.productList = productList;
this.context = context;
}
}
6) now goto your MainActivity.java and paste this code
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<modle> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private testAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new testAdapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
preparedata();
}
private void preparedata() {
model movie = new model("XXX", "Male");
movieList.add(movie);
//add the items according to your wish
//name,gender
//here i have added all items with same name and gender. you can change it
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
}
Hope this helps :)

Related

How to obtain multiple Checkbox states from nested Recycler View?

I have multiple checkboxes (switches in my case), in a nested recycler view. It looks like the following :
I want to be able to retrieve all switch states on this screen when the user goes back and be able to identify which one’s are set to true. For example, I’m looking to obtain something in a similar format to this:
[Item 0, Sub Item 1, TRUE], [Item 0, Sub Item 2, TRUE], [Item 1, Sub Item 0, TRUE] , etc.
My issue is that I’m not exactly sure how to store these switch states. I'm not sure how to get the specific switch values here when they're placed in a nested recycler view.
Here is the code I'm following:
MainActivity
package com.example.recycledviewpoolexample;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rvItem = findViewById(R.id.rv_item);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
ItemAdapter itemAdapter = new ItemAdapter(buildItemList());
rvItem.setAdapter(itemAdapter);
rvItem.setLayoutManager(layoutManager);
}
private List<Item> buildItemList() {
List<Item> itemList = new ArrayList<>();
for (int i=0; i<10; i++) {
Item item = new Item("Item "+i, buildSubItemList());
itemList.add(item);
}
return itemList;
}
private List<SubItem> buildSubItemList() {
List<SubItem> subItemList = new ArrayList<>();
for (int i=0; i<3; i++) {
SubItem subItem = new SubItem("Sub Item "+i, false);
subItemList.add(subItem);
}
return subItemList;
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
/*if Checkboxes are true, store/display them in the logs
EXAMPLE OUTPUT:
Item (String)
SubItem (String)
*/
}
}
Item.java
public class Item {
private String itemTitle;
private List<SubItem> subItemList;
public Item(String itemTitle, List<SubItem> subItemList) {
this.itemTitle = itemTitle;
this.subItemList = subItemList;
}
public String getItemTitle() {
return itemTitle;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public List<SubItem> getSubItemList() {
return subItemList;
}
public void setSubItemList(List<SubItem> subItemList) {
this.subItemList = subItemList;
}
}
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
private List<Item> itemList;
ItemAdapter(List<Item> itemList) {
this.itemList = itemList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_item, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i) {
Item item = itemList.get(i);
itemViewHolder.tvItemTitle.setText(item.getItemTitle());
// Create layout manager with initial prefetch item count
LinearLayoutManager layoutManager = new LinearLayoutManager(
itemViewHolder.rvSubItem.getContext(),
LinearLayoutManager.VERTICAL,
false
);
layoutManager.setInitialPrefetchItemCount(item.getSubItemList().size());
// Create sub item view adapter
SubItemAdapter subItemAdapter = new SubItemAdapter(item.getSubItemList());
itemViewHolder.rvSubItem.setLayoutManager(layoutManager);
itemViewHolder.rvSubItem.setAdapter(subItemAdapter);
itemViewHolder.rvSubItem.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
return itemList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView tvItemTitle;
private RecyclerView rvSubItem;
ItemViewHolder(View itemView) {
super(itemView);
tvItemTitle = itemView.findViewById(R.id.tv_item_title);
rvSubItem = itemView.findViewById(R.id.rv_sub_item);
}
}
}
SubItem.java
package com.example.recycledviewpoolexample;
public class SubItem {
private int subItemImage;
private String subItemTitle;
private boolean checkbox;
public SubItem(String subItemTitle, boolean checkbox) {
this.subItemTitle = subItemTitle;
this.checkbox = checkbox;
}
public int getSubItemImage() {
return subItemImage;
}
public void setSubItemImage(int subItemImage) {
this.subItemImage = subItemImage;
}
public String getSubItemTitle() {
return subItemTitle;
}
public void setSubItemTitle(String subItemTitle) {
this.subItemTitle = subItemTitle;
}
public boolean isSelected() {
return checkbox;
}
public void setCheckbox(boolean checkbox) {
this.checkbox = checkbox;
}
}
SubItemAdapter.java
public class SubItemAdapter extends RecyclerView.Adapter<SubItemAdapter.SubItemViewHolder> {
private List<SubItem> subItemList;
SubItemAdapter(List<SubItem> subItemList) {
this.subItemList = subItemList;
}
#NonNull
#Override
public SubItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_sub_item, viewGroup, false);
return new SubItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SubItemViewHolder subItemViewHolder, int i) {
final SubItem subItem = subItemList.get(i);
subItemViewHolder.tvSubItemTitle.setText(subItem.getSubItemTitle());
subItemViewHolder.checkBox.setOnCheckedChangeListener(null);
subItemViewHolder.checkBox.setChecked(subItem.isSelected());
subItemViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
subItem.setCheckbox(isChecked);
}
});
}
#Override
public int getItemCount() {
return subItemList.size();
}
class SubItemViewHolder extends RecyclerView.ViewHolder {
TextView tvSubItemTitle;
Switch checkBox;
SubItemViewHolder(View itemView) {
super(itemView);
tvSubItemTitle = itemView.findViewById(R.id.tv_sub_item_title);
checkBox = itemView.findViewById(R.id.switch1);
}
}
}
layout_sub_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img_sub_item"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#color/colorPrimaryDark"
android:src="#drawable/ic_launcher_foreground"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/img_sub_item"
android:padding="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_sub_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Sub item title"/>
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
layout_item.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#f3f3f3"
app:cardElevation="8dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12sp"
android:textSize="18sp"
android:text="Item Title"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_sub_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Any help would be appreciated. Thanks!

E/RecyclerView: No adapter attached; skipping layout in fragment

im trying to get data from firestore. but those data don't appears in my fragment activity.
and there is this error: E/RecyclerView: No adapter attached; skipping layout
i can only see the background of frangment activy, where is the error?
SecondFragment.class
public class SecondFragment extends Fragment {
public static final String TAG = "FireLog";
RecyclerView mMainList;
FirebaseFirestore mFirestore;
CollectionReference mRef;
View view;
public List<Offices> officesList;
public OfficesListAdapter officesListAdapter;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.second_layout, container, false);
//Recycler View
mMainList = (RecyclerView) view.findViewById(R.id.main_list);
LinearLayoutManager manager = new LinearLayoutManager(getContext());
mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(getContext()));
mMainList.setAdapter(officesListAdapter);
mFirestore = FirebaseFirestore.getInstance();
officesList = new ArrayList<>();
officesListAdapter = new OfficesListAdapter(officesList);
mFirestore.collection("TICINO").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null){
Log.d(TAG, "Error : " + e.getMessage());
}
for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()) {
if(doc.getType() == DocumentChange.Type.ADDED){
Offices offices = doc.getDocument().toObject(Offices.class);
officesList.add(offices);
officesListAdapter.notifyDataSetChanged();
}
}
}
});
second_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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.RecyclerView
android:id="#+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
OfficeListAdapter.class
public class OfficesListAdapter extends RecyclerView.Adapter<OfficesListAdapter.ViewHolder> {
public List<Offices> officesList;
public OfficesListAdapter(List<Offices> officesList){
this.officesList = officesList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_offices, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.nameText.setText(officesList.get(i).getNameOffices());
viewHolder.cambioText.setText(officesList.get(i).getCambio());
}
#Override
public int getItemCount() {
return officesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView nameText;
public TextView cambioText;
View mView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mView=itemView;
nameText = (TextView) mView.findViewById(R.id.text_view_name_office);
cambioText = (TextView) mView.findViewById(R.id.text_view_cambio_offices);
}
}
}
Offices.class
public class Offices {
String name, cambio;
public Offices(){}
public Offices(String name, String cambio) {
this.name = name;
this.cambio = cambio;
}
public String getNameOffices() {
return name;
}
public void setNameOffices(String name) {
this.name = name;
}
public String getCambio() {
return cambio;
}
public void setCambio(String cambio) {
this.cambio = cambio;
}
}
list_offices.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
app:cardBackgroundColor="#ffffe8">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<TextView
android:id="#+id/text_view_name_office"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_alignParentLeft="true"
android:maxLines="1"
android:ellipsize="end"
android:textAppearance="#style/TextAppearance.AppCompat.Large" />
<TextView
android:id="#+id/text_view_cambio_offices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Description"
android:layout_below="#id/text_view_name_office"/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Try to set the adapter after instantiating it. E.g.:
// Inside OnCreate
//Recycler View
mMainList = (RecyclerView) view.findViewById(R.id.main_list);
LinearLayoutManager manager = new LinearLayoutManager(getContext());
mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(getContext()));
mFirestore = FirebaseFirestore.getInstance();
officesList = new ArrayList<>();
officesListAdapter = new OfficesListAdapter(officesList);
// Here your adapter is initialised
mMainList.setAdapter(officesListAdapter);
Create your adapter object before set it on RecyclerView
// add below method in your adapter class
public void dataChanged(List<Offices> officesList){
this.officesList = officesList;
notifyDataSetChanged();// make sure dont forget to call this method
}
// create adapter object before set it on RecyclerView
LinearLayoutManager manager = new LinearLayoutManager(getContext());
mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(getContext()));
officesListAdapter = new OfficesListAdapter(null);// add this line here
mMainList.setAdapter(officesListAdapter);
mFirestore = FirebaseFirestore.getInstance();
officesList = new ArrayList<>();
// and finally update data on your adapter from your firebase onEvent() method
for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()) {
if(doc.getType() == DocumentChange.Type.ADDED){
Offices offices = doc.getDocument().toObject(Offices.class);
officesList.add(offices);
}
}
officesListAdapter.dataChanged(officesList);// update from here

images and text not showing in cardview

I am using a card view with a recyclerView.The problem I'm having is that the cards are not displaying the images and the text that is supposed to be displayed, all I get is empty cards. any way I could fix this or am I doing something wrong?
avctivitymain xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="8dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
cardsport xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="120dp"
android:layout_height="190dp"
android:id="#+id/car_lay"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:cardview="http://schemas.android.com/tools"
android:layout_margin="5dp"
app:cardCornerRadius="4dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/sport_image"
android:layout_width="match_parent"
android:layout_height="160dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/sport_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="14sp"
android:gravity="center"
android:text="frgrggr"
android:textColor="#2d2d2d"/>
</LinearLayout>
</android.support.v7.widget.CardView>
recyclerview adapter class
import java.util.List;
public class Recycler_view extends RecyclerView.Adapter<Recycler_view.myViewHolder>
{
private Context mContext;
private List<card> mData;
public Recycler_view(Context mContext, List<card> mData)
{
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View v;
LayoutInflater mflate = LayoutInflater.from(mContext);
v = mflate.inflate(R.layout.card_sport,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position)
{
holder.sport_txt.setText(mData.get(position).getType_sport());
holder.image_view.setImageResource(mData.get(position).getImages());
}
#Override
public int getItemCount()
{
return mData.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder
{
TextView sport_txt;
ImageView image_view;
CardView cv;
public myViewHolder(View itemView)
{
super(itemView);
sport_txt = itemView.findViewById(R.id.sport_title);
image_view = itemView.findViewById(R.id.sport_image);
cv = itemView.findViewById(R.id.car_lay);
}
}
}
Main activity java class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
List<card> card_sport;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
card_sport = new ArrayList<>();
// ADDING DATA TO THE CARD ARRAYLIST
card_sport.add(new card("soccer",R.drawable.soccer));
card_sport.add(new card("Cage Fighting",R.drawable.cagef));
card_sport.add(new card("Cricket",R.drawable.cricket));
card_sport.add(new card("WaterPolo",R.drawable.polo));
card_sport.add(new card("Running",R.drawable.runman));
card_sport.add(new card("Swimming",R.drawable.swim));
card_sport.add(new card("Rugby",R.drawable.rugby));
RecyclerView rv = findViewById(R.id.recyclerview);
Recycler_view re_adapter = new Recycler_view(this, card_sport);
rv.setLayoutManager(new GridLayoutManager(this,2));
rv.setAdapter(re_adapter);
}
}
card java class for getters and setters
package com.example.dalian.cool_jungle;
public class card
{
private String type_sport;
private int images;
public card()
{
}
public card(String type_sport,int images)
{
type_sport= type_sport;
images = images;
}
public String getType_sport()
{
return type_sport;
}
public int getImages()
{
return images;
}
public void setType_sport()
{
type_sport =type_sport;
}
public void setImages()
{
images = images;
}
}
log
line 17
line 47
after a taken "this" out my card class it just shows blank cards
Your all above code are fine. There will no problem if you made your card object correctly. That may be like:
public class card {
private String type_sport;
private int image;
public card(String type_sport, int image) {
this.type_sport = type_sport;
this.image = image;
}
public String getType_sport() {
return type_sport;
}
public void setType_sport(String type_sport) {
this.type_sport = type_sport;
}
public int getImages() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
You don't need to pass the context in, you can get it from the parent viewgroup. You also don't need to make the view holder a static class, that might help.

Simply expanding a recyclerview to show a TextView

I've explored many ways to achieve this. But I'm much confused now. I tried many Githubs libraries but got confused. Also tried this but I don't think it allows a textview to be shown in expanded view: http://bignerdranch.github.io/expandable-recycler-view/
WHAT I WANT: A simple Recyclerview fetching some text from server for different items. On each item click, a layout or view should be expanded and TextView should become visible with respective fetched text from the server.
I have a simple RecyclerView with code following:
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<List> android_versions;
private Context context;
int i =0;
public DataAdapter(Context context,ArrayList<List> android_versions) {
this.context = context;
this.android_versions = android_versions;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.tv_android.setText(android_versions.get(i).getAndroid_version_name());
}
#Override
public int getItemCount() {
return android_versions.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_android;
public ViewHolder(View view) {
super(view);
tv_android = (TextView)view.findViewById(R.id.tv_android);
}
}
List.java (Some functions aren't being used as of now)
public class List {
private String android_version_name;
private String descr;
private int android_image_url;
private String android_image_url1;
public String getAndroid_version_name() {
return android_version_name;
}
public String getDescr(){ return descr;}
public void setDescr(String descr) {
this.descr = descr;
}
public void setAndroid_version_name(String android_version_name) {
this.android_version_name = android_version_name;
}
public int getAndroid_image_url() {
return android_image_url;
}
public String getAndroid_image_url1() {
return android_image_url1;
}
public void setAndroid_image_url(int android_image_url) {
this.android_image_url = android_image_url;
}
public void setAndroid_image_url1(String android_image_url1) {
this.android_image_url1 = android_image_url1;
}
}
row_layout.xml
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
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_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp"
android:background="#drawable/custom_bg"
android:clickable="true"
android:translationZ="3dp"
android:elevation="1dp"
android:focusable="true">
<RelativeLayout
android:layout_marginLeft="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/custom_bg">
<TextView
android:layout_marginTop="10dp"
android:textSize="20sp"
android:layout_marginRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_android"
android:textStyle="normal"
android:layout_centerVertical="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Work.java (It's a fragment)
String[] sublist={
"English",
"Hindi"
};
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
rcl = (RecyclerView) getActivity().findViewById(R.id.homeworklist);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rcl.setLayoutManager(layoutManager);
dataAdapter = new DataAdapter(getActivity(), new ArrayList<>(prepareData()));
rcl.setAdapter(dataAdapter);
}
public ArrayList prepareData(){
ArrayList android_version = new ArrayList<>();
for(int i=0;i<sublist.length;i++){
List androidVersion = new List();
androidVersion.setAndroid_version_name(sublist[i]);
android_version.add(androidVersion);
break;
}
return android_version;
}

NullPointerException while listview fills

I have MainActivity class where I parse an HTML page with JSOUP and I also have custom adapter which store data for each row in my ListView. So I get data with JSOUP and it's ok as my LogCat tell me. But when I try to put data to my ListView I get an error.
My activity_main layout:
<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" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
My list_item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/thumbImageNews"
android:layout_marginLeft="10dp"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/titleNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/thumbImageNews"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="5dp"
android:text=""
android:textColor="#ff0d075c"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/date2News"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbImageNews"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="2dp"
android:text=""
android:textColor="#ff585858"
android:textSize="12sp"
android:layout_marginLeft="10dp"/>
</RelativeLayout>
CustomListAdapter activity:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.titleNews);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date2News);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImageNews);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
// holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
FeedItem class to store data for each row:
public class FeedItem implements Serializable {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
private String date;
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
private String attachmentUrl;
}
And my MainActivity class where executes all main functions:
public class MainActivity extends Activity {
public Elements title;
public Elements picture;
final String ATTRIBUTE_NAME_TEXT = "text";
final String ATTRIBUTE_NAME_IMAGE = "image";
final String ATTRIBUTE_NAME_DATE = "date";
private ArrayList<FeedItem> feedList = null;
private ListView feedListView = null;
public CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
feedListView = (ListView) findViewById(R.id.listView1);
new NewThread().execute();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
Document doc;
try {
doc = Jsoup.connect("http://example.com/news/").get();
title = doc.select("h2[class=et_pt_title]");
picture = doc.select("img");
for (Element titles : title) {
FeedItem item = new FeedItem();
item.setTitle(titles.text());
Log.w("title",""+item.getTitle());
feedList.add(item);
}
for (Element img : picture){
String iurl;
iurl = img.absUrl("src");
FeedItem item = new FeedItem();
item.setAttachmentUrl(iurl);
Log.w("imgUrl",""+item.getAttachmentUrl());
feedList.add(item);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
adapter = new CustomListAdapter(MainActivity.this,feedList);
feedListView.setAdapter(adapter);
}
}
}
So my problem is that when feedList.add(item); executes I get NullPointerException, but Log.w("title",""+item.getTitle()); shows me that everything is ok. What I do wrong?
Your feedList is not initialized.
So before adding items to it, please initialize.
ArrayList<FeedItem> feedList = new ArrayList<FeedItem> ;
Add the above line before you call the AsyncTask i.e. before new NewThread().execute();
It should look like this
feedList = new ArrayList<FeedItem> ;
new NewThread().execute();
Your mistake was you have just declared this
private ArrayList<FeedItem> feedList = null;
not initialized. So just initialize on onCreate() method.
feedList = new ArrayList<FeedItem> ;
private ArrayList<FeedItem> feedList = null;
without create object you are adding data in arraylist
feedList.add(item);
please create object
feedList = new ArrayList<FeedItem>()
than Add
feedList.add(item);

Categories

Resources