unable to retrieve data from Firebase using Fragments in Android Studio - android

Hy! I am trying to retrieve data from Firebase but unable to show the pictures and names of categories on the fragment layout. I can't understand whether its Firebase error or Layout error because on selecting fragment imageview or textview are also not been shown. This is the code from categories fragment in which recyclerview is used in fragment layout XML file.
public class CategoriesFragment extends Fragment {
View myfragment;
RecyclerView listCategory;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category,CategoryViewHolder> adapter;
FirebaseDatabase database;
DatabaseReference categories;
public static CategoriesFragment newInstance(){
CategoriesFragment categoriesFragment = new CategoriesFragment();
return categoriesFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
categories = database.getReference("Category");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myfragment = inflater.inflate(R.layout.fragment_categories,container,false);
listCategory = (RecyclerView)myfragment.findViewById(R.id.listcategory);
listCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(container.getContext());
listCategory.setLayoutManager(layoutManager);
loadCategories();
return myfragment;
}
private void loadCategories() {
adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(
Category.class,
R.layout.category_layout,
CategoryViewHolder.class,
categories
) {
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, final Category model, int position) {
viewHolder.category_name.setText(model.getName());
Picasso.with(getActivity())
.load(model.getImage())
.into(viewHolder.category_image);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(getActivity(),String.format("%s|%s",adapter.getRef(position).getKey(),model.getName()),Toast.LENGTH_LONG).show();
}
});
}
};
adapter.notifyDataSetChanged();
listCategory.setAdapter(adapter);
}`

Related

Kotlin Recyclerview send data to fragment [duplicate]

I have a recyclerView populated in a Fragment and I want to Launch a new Fragment and pass data from the adapter ,I try to use Bundles but it always give a null value this my Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition());
}
}
and this is my new Fragment that I want to launch
public class FragmentB extends Fragment {
TextView textview;
TextView textView2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.tv_name);
textView2= (TextView) view.findViewById(R.id.tv_job);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments!=null){
String name= arguments.get("NAME").toString();
String job= arguments.get("JOB").toString();
textview.setText(name);
textView2.setText(job);}
}
}
this is how I connect Fragment and recyclerview Adapter
with interface
public interface FragmentCommunication {
void respond(int position);
}
and this the Fragment where the recyclerview is populated
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position) {
FragmentB fragmentB=new FragmentB();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
and my mainActivity class is just add the RecyclerViewFragment
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerViewFragment fragment=new RecyclerViewFragment();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragment).commit();
}
}
so what is the right way to launch fragmentB and pass the data from recyclerview Adapter to fragmentB
thank you guys for the answer,I solved the problem using an interface with String values to connect the adapter with the fragment that contains the recyclerview and the other fragment here is what I did exactly :
this is the interface
public interface FragmentCommunication {
void respond(int position,String name,String job);
}
and this is the adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition(),mList.get(getAdapterPosition()).name,mList.get(getAdapterPosition()).job);
}
}
}
the fragment that contains the recyclerview
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position,String name,String job) {
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",name);
bundle.putString("JOB",job);
fragmentB.setArguments(bundle);
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
this is the fragmentB where I get the Strings from the Adapter
public class FragmentB extends Fragment {
TextView textview;
TextView textview2;
String name;
String job;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name=getArguments().getString("NAME");
job=getArguments().getString("JOB");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.getName);
textview2= (TextView) view.findViewById(R.id.getJob);
textview.setText(name);
textview2.setText(job);
return view;
}
}
If you are working with kotlin, the solution is much simpler.
Original Answer here
pass the function val itemClick: (Int) -> Unit to your adapter.
class MyRecyclerViewAdapter(params , val itemClick: (Int) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
itemView.setOnClickListener( {itemClick(layoutPosition)} )
}
}
In your fragment use the returned value position
val myAdapter = MyRecyclerViewAdapter(params) { position ->
// do something
}
Either creating a listener interface in the adapter or using regular old getters, if I understand your question correctly.
You need to pass the Bundle to the fragment through the setArguments(Bundle args) method. Since you have not set arguments, the bundle you try to extract in your Fragment resolves to null.
You have the right idea with using a Bundle. You just need to pass it to the Fragment by calling setArguments(). Then you retrieve the Bundle in your Fragment with getArguments().
Note that instead of mList.get(position).name, you can do current.name. Similarly for job.
Another part of the problem is that you create FragmentB on two different places. In one place you also call setArguments() but do not show the fragment. In the other you show the fragment but do not call setArguments(). If you really need to do this from multiple parts of your code you should write a method to avoid these inconsistencies.

how can i create a custom list in android fragment with onClick for different items in list?

can i use ListFragment to achieve what I said above or i need a custom recycler view inside a fragment, I tried to put a recycler view inside fragment but i didn't know how to make the onClick for recycler view work with fragment so it passes data to another fragment or another activity in case of multi-pane UI, so can i use list fragment or my only choice is recycler view, if it's then how can I do it in recycler view ?
my MainActivity which has a fragment that contains the recycler view
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.main_fragment_container);
if (fragment == null) {
fragment = new FragmentRecyclerList();
fm.beginTransaction()
.add(R.id.main_fragment_container, fragment)
.commit();
}
}
}
my fragment which contains the recycler view
public class FragmentRecyclerList extends Fragment implements MyDialog.OnInputSelected {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private List<String> titles;
private FloatingActionButton fab;
public FragmentRecyclerList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_recycler_list, container, false);
}
void showDialog() {
MyDialog myDialog = new MyDialog();
myDialog.setTargetFragment(FragmentRecyclerList.this, 1);
myDialog.show(getFragmentManager(), "MyDialog");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = getView().findViewById(R.id.recyclerview);
fab = getView().findViewById(R.id.floatingActionButton);
titles = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewAdapter = new RecyclerViewAdapter(getActivity(), titles);
recyclerView.setAdapter(recyclerViewAdapter);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
}
my recycler view adapter
public class RecyclerViewAdapter extends
RecyclerView.Adapter {
private Context context;
private List<String> titles;
public RecyclerViewAdapter(Context context, List<String> titles) {
this.context = context;
this.titles = titles;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_wallpaper
, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String title = titles.get(position);
holder.tvTitle.setText(title);
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvTitle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
View v = itemView;
tvTitle = itemView.findViewById(R.id.row_title);
}
}
}

Dynamic Data in TabLayout and Viewpager Fragment is Out of sync

I have a TabLayout, where the data is populated from web service which contain {"TOPS","LAUNDRY","BEDDING"...}.
This data is stored in a list which is passed into the adapter.
myTabAdapter = new MyTabAdapter(getSupportFragmentManager(),tabListings);
viewpager.setAdapter(myTabAdapter);
tabList.setupWithViewPager(viewpager);
And my TabAdapter.
public class MyTabAdapter extends FragmentStatePagerAdapter {
private ArrayList<TabListing> tabListings;
String item;
private Bundle bundle;
public MyTabAdapter(FragmentManager supportFragmentManager, ArrayList<TabListing> tabListings) {
super(supportFragmentManager);
this.tabListings = tabListings;
}
#Override
public Fragment getItem(int position) {
TabListing l = tabListings.get(position);
String a = l.getName();
bundle = new Bundle();
bundle.putString("item", a);
return OneFragment.newInstance(0, bundle);
}
#Override
public int getCount() {
return tabListings.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
TabListing l = tabListings.get(position);
String a = l.getName();
return a;
}
}
In the getItem() method I am passing the name using bundle to fragment with new instance method.
When the data gets into the fragment like "TOPS", it is to be passed in the database Reference field of Firebase to populate my recyclerview.
My problem is when i run the app, the get the data for "LAUNDRY" instead of "TOPS" in the first run. When I swipe 2 index forward to "BEDDING", the data is synced according to the tabs. I cannot understand what is the problem.
My Fragment class.
public class OneFragment extends Fragment {
private static String a;
RecyclerView recyclerview;
AdapterToActivity act;
Bundle args;
ListingAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mReference;
ContentLoadingProgressBar pBar;
int position;
ArrayList<ItemList> itm = new ArrayList<>();
public OneFragment() {
}
public static OneFragment newInstance(int position, Bundle item) {
Bundle args = item;
a = args.getString("item");
OneFragment fragment = new OneFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one, container, false);
recyclerview = v.findViewById(R.id.all_product_list);
pBar = v.findViewById(R.id.progress);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
recyclerview.setLayoutManager(layoutManager);
adapter = new ListingAdapter(getActivity(),itm,a);
args = getArguments();
RecyclerViewAdapterMethod();
return v;
}
#Override
public void onStart() {
super.onStart();
pBar.show();
adapter.notifyDataSetChanged();
pBar.hide();
}
private void RecyclerViewAdapterMethod() {
pBar.show();
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference(a);
mReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ItemList l;
l = dataSnapshot.getValue(ItemList.class);
itm.add(l);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
pBar.hide();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

RecyclerView with sqlite db working in activity but not working in fragments

I am the beginner in android
I have found many answers of a similar question but no answer unfortunately worked for me
I am using recylcerView using card view to show student data .I am taking Data from My sqlite db.
My code works fine in activity but because of navigation drawer i put it in a fragment and it is showing blank.
here is my activity and fragment code.
MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private PersonDBHelper dbHelper;
private MyCustomAdapter adapter;
private String filter = "";
TextView textView;
public static int navItemIndex = 0;
Toolbar toolbar;
private DrawerLayout mDrawerLayout;
FloatingActionButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.person_list);
/* toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);*/
mDrawerLayout=findViewById(R.id.drawer_layout);
NavigationView navigationView=findViewById(R.id.nav_view);
mRecyclerView = (RecyclerView)findViewById(R.id.recycler_view);
textView=findViewById(R.id.empty_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
//populate recyclerview
populaterecyclerView(filter);
button=findViewById(R.id.fab_add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToAddUserActivity();
}
});
}
private void populaterecyclerView(String filter) {
dbHelper = new PersonDBHelper(this);
adapter = new MyCustomAdapter(dbHelper.peopleList(filter), this, mRecyclerView);
mRecyclerView.setAdapter(adapter);
}
private void goToAddUserActivity(){
Intent intent = new Intent(MainActivity.this, AddRecordActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
this is working fine but for the fragment i did following changes
StudentListFragment()
ublic class StudentListFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private PersonDBHelper dbHelper;
private MyCustomAdapter adapter;
FloatingActionButton button;
private String filter = "";
View rootView;
#RequiresApi(api = Build.VERSION_CODES.M)
public static StudentListFragment newInstance(){
StudentListFragment studentListFragment = new StudentListFragment();
Bundle args=new Bundle();
studentListFragment.setArguments(args);
return studentListFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
rootView=inflater.inflate(R.layout.person_list,container,false);
mRecyclerView=rootView.findViewById(R.id.recycler_view);
dbHelper = new PersonDBHelper(getContext());
adapter = new MyCustomAdapter(dbHelper.peopleList(filter), getContext(), mRecyclerView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
button=rootView.findViewById(R.id.fab_add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToAddUserActivity();
}
});
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(false);
ensureList();
}
private void goToAddUserActivity() {
Intent intent = new Intent(getActivity(), AddRecordActivity.class);
startActivity(intent);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("StudentList");
}
public void ensureList(){
if (dbHelper != null) {
return;
}
View root = getView();
if (root == null) {
throw new IllegalStateException("Content view not yet created");
} }
}
i am calling this fragment in navigation drawer code is working but not displaying any data. If i put this fragment first in navigation drawer menu means when navigation drawer activity starts this fragment will get open.In such case it is displaying my cards(my data) but if i switch to other fragment and return back to this fragment it is showing blank
In fragment, onCreateView() method, please inflate your root view and return it immediately, do not do anything else.
Implement your logic to onViewCreated(). something like this :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
rootView=inflater.inflate(R.layout.person_list,container,false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("StudentList");
mRecyclerView=view.findViewById(R.id.recycler_view);
dbHelper = new PersonDBHelper(getContext());
adapter = new MyCustomAdapter(dbHelper.peopleList(filter), getContext(), mRecyclerView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
button=view.findViewById(R.id.fab_add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToAddUserActivity();
}
});
}
could you please try this. And make sure you have items in the list.

Displaying data getting fetched asynchronously in a RecyclerView in Fragment

I am trying to load the data list asynchronously and showing it on RecyclerView in fragments. However, the same implementation works for Activity class but fails for Fragment:
public class ItemThreeFragment extends Fragment {
String email;
private CompositeSubscription mSubscriptions;
HistoryAdapter historyAdapter;
RecyclerView recyclerView;
public static ItemThreeFragment newInstance() {
ItemThreeFragment fragment = new ItemThreeFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
email = ((BaseApplication) getActivity().getApplication()).getEmail();
mSubscriptions = new CompositeSubscription();
getUserHistory(email);
}
private void getUserHistory(String email) {
mSubscriptions.add(NetworkUtil.generic().getUserCheckinInfo(email)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleCheckInInfoResponse,this::handleError));
}
private void handleCheckInInfoResponse(List<Checkin> checkins) {
System.out.println(checkins);
historyAdapter = new HistoryAdapter(this.getActivity(), checkins);
recyclerView.setAdapter(historyAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
private void handleError(Throwable throwable) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_three, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.historyList);
return rootView;
}
}
Any kind of suggestions will be highly appreciated.
try to set the adapter in onCreateView() instead of onCreate.
Check for data
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(historyAdapter);
Use these two lines onCreateView after you have fetched the data.

Categories

Resources