RecyclerView won't display my database content - android

I have a database of Users and I'm trying to use a RecyclerView to display every User entry I have. From my logs, I can tell that my RecyclerView isn't even being interacted with. Here is the class where I call it:
public class WelcomePage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_page);
FragmentManager manager = getFragmentManager();
RecyclerFragment mRecyclerFragment = new RecyclerFragment();
if(mRecyclerFragment == null) {
manager.beginTransaction()
.add(R.id.recycler, mRecyclerFragment)
.commit();
}
}
}
This is my holder class:
public class RecyclerHolder extends RecyclerView.ViewHolder{
private static final String TAG = "RecyclerHolder";
private TextView mFullName;
private TextView mBirthDate;
private TextView mHomeTown;
private TextView mBio;
User mUser;
RecyclerHolder(View itemView){
super(itemView);
mFullName = (TextView)itemView.findViewById(R.id.text_view_name);
mBirthDate = (TextView)itemView.findViewById(R.id.text_view_birthday);
mHomeTown = (TextView)itemView.findViewById(R.id.text_view_hometown);
mBio = (TextView)itemView.findViewById(R.id.text_view_bio);
public void bind(User user) {
mUser = user;
mFullName.setText(user.getFullName());
mBirthDate.setText(user.getBirthDate().toString());
mHomeTown.setText(user.getHomeTown());
mBio.setText(user.getBio());
}
}
Here's my adapter class:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerHolder> {
private ArrayList<User> mUsers;
public RecyclerAdapter(ArrayList<User> user) {
mUsers = user;
}
#Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.view_recycler, parent, false);
RecyclerHolder holder = new RecyclerHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerHolder holder, int position){
holder.bind(mUsers.get(position));
}
#Override
public int getItemCount() {
return mUsers.size();
}
}
Here's my fragment class:
public class RecyclerFragment extends Fragment {
private RecyclerView mRecyclerView;
DBCursorWrapper db;
public RecyclerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler, container, false);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recycler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
RecyclerAdapter adapter = new RecyclerAdapter(db.getUserList());
mRecyclerView.setAdapter(adapter);
return view;
}
}
Here is the XML for my holder:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_recycler">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>
</LinearLayout>
Here is my XML for my fragment:
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.csc214.just4kas.project02.RecyclerFragment">
</android.support.v7.widget.RecyclerView>
Here is my XML for where I call my RecyclerView:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.csc214.just4kas.project02.WelcomePage">
</FrameLayout>
The getUserList() has been tested individually and works perfectly!
Any help would be super appreciated! I just want a RecyclerView of all the contents in my database!! Thanks!

I think you may be using the wrong layout when you replace add it to the main activity. try (R.id.frame_layout_recycler_view) instead or R.id.recycler.
Or there might be a issue when use the database in this context.

Related

How to show recycler view in the fragments of tablayout?

This is the data file which I have prepared in order to put data in the recycler view of my fragment
public class Data
{
public static ArrayList<Information> getData(){
ArrayList<Information> data= new ArrayList<>();
int [] images={
R.drawable.fuel,
R.drawable.milage,
R.drawable.serviceicon,
R.drawable.engine,
R.drawable.carbattery
};
String[] InformationAbout = {"245 Est miles to empty","4768 Miles Drove", "2 service compaings","245 EST mile to empty","72% battery level is good"};
for (int i=0;i<=images.length-1;i++)
{
Information current= new Information();
current.title=InformationAbout[i];
current.imageId=images[i];
data.add(current);
}
return data;
}
}
This is the information class which I have created in order to assign ID.
public class Information
{
public int imageId; //Reference to all the images in the drawable folder
public String title;
}
The listadapter which I have created in order to serve the recycler view and bind it to the view:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MyViewHolder> {
private Activity context;
ArrayList<Information> data;
//LayoutInflater inflator;
public ListAdapter(Activity context , ArrayList<Information> data){
this.context = context;
this.data=data;
//this.inflator = LayoutInflater.from(context);
}
#Override
public ListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = context.getLayoutInflater() ;
View view=inflater.inflate(R.layout.list_single,parent,false);
MyViewHolder myViewHolder= new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(ListAdapter.MyViewHolder holder, int position) {
holder.textview.setText(data.get(position).title);
holder.imageView.setImageResource(data.get(position).imageId);
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView textview;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textview = (TextView) itemView.findViewById(R.id.text_corresponding_image);
imageView = (ImageView) itemView.findViewById(R.id.icon_health_report);
}
}
}
This is the XML file which I am trying to serve in the adapter of the recyclerview.
list_single.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_single"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/icon_health_report"
android:layout_width="#dimen/tabel_image_width"
android:layout_height="#dimen/table_image_height"/>
<TextView
android:id="#+id/text_corresponding_image"
android:layout_width="wrap_content"
android:layout_height="20dp"/>
</LinearLayout>
This is the layout of the fragment:
<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="com.example.a129346.applicationpoc.Fragments.HealthReportFragmentTab">
<android.support.v7.widget.RecyclerView
android:id="#+id/vechile_report_lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
This is the fragmenttab.java class where I am initiating the recycler view of the layout:
public class HealthReportFragmentTab extends Fragment {
private static String TAG = HealthReportFragmentTab.class.getSimpleName();
private RecyclerView recyclerView;
private ListAdapter mylistAdapter;
private HealthHistoryFragmentTab.OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.health_report_fragment, container, false);
initViews(rootview);
return rootview;
}
private void initViews(View view){
recyclerView = (RecyclerView) view.findViewById(R.id.vechile_report_lv);
mylistAdapter = new ListAdapter(getActivity(), Data.getData());
recyclerView.setAdapter(mylistAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}
but I am not able to get the data on the this vehicle health tab. I want the images in the image array and text in front of the image which is the categories string array.
In the fragmentTab.java class, simply add:
public class HealthReportFragmentTab extends Fragment {
private static String TAG = HealthReportFragmentTab.class.getSimpleName();
private RecyclerView recyclerView;
private ListAdapter mylistAdapter;
private HealthHistoryFragmentTab.OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.health_report_fragment, container, false);
initViews(rootview);
return rootview;
}
private void initViews(View view){
recyclerView = (RecyclerView) view.findViewById(R.id.vechile_report_lv);
mylistAdapter = new ListAdapter(getActivity(), Data.getData());
recyclerView.setAdapter(mylistAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}
In place of getActivity I applied getContext() method because it a fragment and then it needs a context in order to setlayout.

Why does Recycler view gives null pointer exception?

I am using RecyclerView in a fragment, it is generate a NullPointerException and I cannot understand the reason.
Here is my fragment activity:
public class Recharges extends Fragment {
public RecyclerView recyclerView;
private List<GetRecharge> rechargeList = new ArrayList<>();
public RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
ImageView image1, image2;
#Nullable #Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
View rootView = inflater.inflate(R.layout.recharges, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
final FragmentActivity c = getActivity();
layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapterrecharge(rechargeList);
recyclerView.setAdapter(adapter);
prepareRechargeData();
return rootView;
}
private void prepareRechargeData() {
GetRecharge recharge = new GetRecharge("Mad Max: Fury Road" );
rechargeList.add(recharge);
adapter.notifyDataSetChanged();
}
}
Here the adapter class:
public class Adapterrecharge extends RecyclerView.Adapter<Adapterrecharge.MyViewHolder> {
private List<GetRecharge> rechargeList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public Adapterrecharge(List<GetRecharge> rechargeList) {
this.rechargeList = rechargeList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rechargelist, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
GetRecharge recharge = rechargeList.get(position);
holder.title.setText(recharge.getTitle());
}
#Override
public int getItemCount() {
return rechargeList.size();
}
}
I seem to be inflating the correct layout but still getting the error.
here is the logcat error
java.lang.NullPointerException
at com.example.aadesh.walletuncle.Adapterrecharge.onBindViewHolder(Adapterrecharge.java:53)
at com.example.aadesh.walletuncle.Adapterrecharge.onBindViewHolder(Adapterrecharge.java:21)
here is the recyclerview item layout.
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"/>
here is the main layout
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<TextView
android:text="Recharge"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_weight="1" />
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="#+id/recyclerview1">
</android.support.v7.widget.RecyclerView>
there are couple of problems
you are populating prepareRechargeData() list data after you have set your adapter - so your list rechargelist doesn't have any data
in your onCreateViewHolder() your are using wrong layout R.layout.rechargelist
in your view Holder you are giving wrong id for textview R.id.title
try this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
View rootView = inflater.inflate(R.layout.recharges, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
final FragmentActivity c = getActivity();
layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
/*recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter((RecyclerView.Adapter) adapter);*/
prepareRechargeData();
adapter = new Adapterrecharge(rechargeList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
Change your adapter to:
public class Adapterrecharge extends RecyclerView.Adapter<Adapterrecharge.MyViewHolder> {
private List<GetRecharge> rechargeList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.text);
}
}
public Adapterrecharge(List<GetRecharge> rechargeList) {
this.rechargeList = rechargeList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_item_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
GetRecharge recharge = rechargeList.get(position);
holder.title.setText(recharge.getTitle());
}
#Override
public int getItemCount() {
return rechargeList.size();
}
}
You are miss matching id of Textview.
Instead of
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"/>
</LinearLayout>
Use this
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title"/>
</LinearLayout>
As you are using wrong id of Textview in MyViewHolder class.
The problem is due to mismatch ids. ID of TextView in xml ("text") and the one inflated in ViewHolder class ("title") are different.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"/>
Adapter class
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}

My views are giving me a null pointer exception

In my app,I get some data from my server. They are displayed fine,but when I pass them in my Detailed Fragment,then all views are null:(.
So here is my code.
public class MainActivityFragment extends Fragment {
public static final String TAG = "AelApp";
public static ArrayList<MyModel> listItemsList;
RecyclerView myList;
public static MatchReportsAdapter adapter;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMatchReport();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Match Report");
View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
listItemsList = new ArrayList<>();
myList = (RecyclerView)rootView.findViewById(R.id.listview_match_reports);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
myList.setHasFixedSize(true);
myList.setLayoutManager(linearLayoutManager);
adapter = new MatchReportsAdapter(getActivity(), listItemsList);
myList.setAdapter(adapter);
return rootView;
}
public void updateMatchReport(){
Intent i = new Intent(getActivity(), MatchReport.class);
getActivity().startService(i);
}
}
Adapter
public class MatchReportsAdapter extends
RecyclerView.Adapter<MatchReportsAdapter.RowHolder>{
private List<MyModel> reportsList;
private Context mContext;
private ImageLoader mImageLoader;
private int focused = 0;
public MatchReportsAdapter(Activity activity, List<MyModel> reportsLists){
this.reportsList = reportsLists;
this.mContext=activity;
}
#Override
public RowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items,null);
final RowHolder holder = new RowHolder(v);
return holder;
}
#Override
public void onBindViewHolder(RowHolder holder, int position) {
final MyModel listItems = reportsList.get(position);
holder.itemView.setSelected(focused==position);
holder.getLayoutPosition();
mImageLoader = AppController.getInstance().getImageLoader();
holder.thumbnail.setImageUrl(listItems.getImage(),mImageLoader);
holder.thumbnail.setDefaultImageResId(R.drawable.reddit_placeholder);
holder.name.setText(Html.fromHtml(listItems.getTitle()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String article = listItems.getArticle();
String image = listItems.getImage();
Intent i = new Intent(mContext, DetailedActivity.class);
i.putExtra("articleKey",article);
i.putExtra("imageKey",image);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return reportsList.size();
}
public class RowHolder extends RecyclerView.ViewHolder{
protected NetworkImageView thumbnail;
protected TextView name;
protected RelativeLayout relativeLayout;
public RowHolder(View itemView) {
super(itemView);
this.relativeLayout = (RelativeLayout)
itemView.findViewById(R.id.recLayout);
this.thumbnail =
(NetworkImageView)itemView.findViewById(R.id.thumbnail);
this.name = (TextView)itemView.findViewById(R.id.title);
}
}
}
DetailedActivity
public class DetailedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed);
if(savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction()
.add(R.id.detailed_match_reports,new DetailedActivityFragment())
.commit();
}
}
}
DetailedActivityFragment
public class DetailedActivityFragment extends Fragment {
TextView articleTextView;
String image;
String article;
ImageView imageView;
public DetailedActivityFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_detailed_activity, container, false);
articleTextView = (TextView)getActivity().findViewById(R.id.articleTextView);
imageView = (ImageView)getActivity().findViewById(R.id.imageNews);
Intent i = getActivity().getIntent();
article = i.getStringExtra("articleKey");
image = i.getStringExtra("imageKey");
Picasso.with(getActivity()).load(image).into(imageView);
articleTextView.setText(article);
return v;
}
}
All of my data are passed after clicking a row good. I know this as I debug the following lines.
article = i.getStringExtra("articleKey");
image = i.getStringExtra("imageKey");
and see that both String variables are not null. However,the both views(TextView,ImageView) of my detailed fragment are null.
Maybe I am doing something wrong with my xml file,and I don't see it.
activity_main.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"
android:id="#+id/match_reports"
tools:context="theo.testing.androidservices.fragments.MainActivityFragment">
</FrameLayout>
fragment_main_activity
<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"
android:id="#+id/recLayout"
tools:context=".activities.MainActivity"
android:background="#fff">
<android.support.v7.widget.RecyclerView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listview_match_reports"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
/>
</RelativeLayout>
activity_detailed.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/detailed_match_reports"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="theo.testing.androidservices.activities.DetailedActivity"
tools:ignore="MergeRootFrame">
</FrameLayout>
and finally
fragment_detailed_activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageNews"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="xcvxcvxcv"
android:textColor="#000"
android:layout_marginTop="5dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/articleTextView"/>
</ScrollView>
What am I missing?
Thanks
Theo.
Change these
articleTextView = (TextView)getActivity().findViewById(R.id.articleTextView);
imageView = (ImageView)getActivity().findViewById(R.id.imageNews);
to
articleTextView = (TextView)v.findViewById(R.id.articleTextView);
imageView = (ImageView)v.findViewById(R.id.imageNews);
You'r passing data to DetailActivity. So first retrieve in DetailActivity and then pass to DetailFragment.
Also you need to pass data to DetailFragment using Bundle with setArguments(bundle)
Your Textview articleTextView is in the fragment but you are finding it in the activitys xml:
articleTextView = (TextView)getActivity().findViewById(R.id.articleTextView);
insetad you should do:
articleTextView = (TextView)(v.findViewById(R.id.articleTextView));
Do the same for Imageviewl.

Open Fragment OnClick on Recyclerview item from ApI

I am getting data from API in recycleview using AQuery but now i want to open fragment from API onclick on recyclerview item so how can i implement this.
I want to do same as Instagram app,like on home page when we click on name we get all the details of users on another fragment.
//CouponFragment.java
public class CouponFragment extends Fragment implements CouponList.OnActionCompleted{
private RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
recyclerView = new RecyclerView(getActivity());
return recyclerView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> coupons = new ArrayList<>();
coupons.add("Tamil");
coupons.add("English");
coupons.add("Malay");
coupons.add("Chinese");
recyclerView.setAdapter(new CouponList(coupons,CouponFragment.this));
}
#Override
public void OnClick(Coupon coupon){
//new fragment
CouponDetails couponDetails = new CouponDetails();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_container, couponDetails);
//R.id.home_container is your FrameLayout id
transaction.addToBackStack("couponDetails");
transaction.commit();
}
}
cardview_coupon_info.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/tools"
android:foreground="?android:attr/selectableItemBackground"
android:transitionName="coupon_info_card"
android:id="#+id/coupon_info_card"
android:clickable="true"
android:layout_margin="#dimen/item_margin"
card_view:cardElevation="6dp"
card_view:cardCornerRadius="4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/coupon_description"
android:gravity="start"
android:layout_margin="4dp" />
</android.support.v7.widget.CardView>
CouponList.java (Recyclerview adapter)
public class CouponList extends RecyclerView.Adapter<CouponList.ViewHolder> {
private ArrayList<String> coupons;
private OnActionCompleted callback;
public CouponList(ArrayList<String> coupons,OnActionCompleted callback)
{
this.coupons = coupons;
this.callback = callback;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_coupon_info,parent,false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.description.setText(coupons.get(position);
}
#Override
public int getItemCount() {
return coupons.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView description;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.coupon_description);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String coupon = coupons.get(getAdapterPosition());
callback.OnClick(coupon);
}
}
public interface OnActionCompleted {
public void OnClick(Coupon coupon);
}
}
You can use this in Activity as well for easy implementation for multiple widget clicks in recycler view item :)
Do the following in your recycler view item onClick.
FragmentManager fm = getFragmentManager();// If you're in an activity.
FragmentManager fm = getSupportFragmentManager();// If you're already inside another fragment
YourFragment yfObj = new YourFragment();
fm.beginTransaction().replace(R.id.fragmentContainer, yfObj).commit();
Here, fm is the FragmentManager object, with which only you can conduct a fragment transaction, such as loading a new fragment.
yfObj is the object of the fragment class that you want to load.
R.id.fragmentContainer is the id of the container layout you have declared in your XML file, where you want to load the fragment.
Hope this helps !

How to create a cardView programatically?

So I have this list of city objects (which contain an image, the name of the city, and a integer value). And for each of these city objects I want to programatically create a new cardView and insert it into a fragment. Currently, nothing shows up...
Here is my fragment xml code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Here is the code for my fragment activity.
public class FragmentCards extends Fragment
{
private ArrayList<CityFolders> cityFolders = new ArrayList<>();
private OnCardsFragmentListener mListener;
private LinearLayout linearLayout;
private View view;
public FragmentCards() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment_cards, container, false);
setUpLinearLayout();
setUpCityFolders();
//TextView myText = (TextView) view.findViewById(R.id.fragCards_numberOfCardsTextContent);
//Toast.makeText(getActivity(), myText.getText(), Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_fragment_cards, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnCardsFragmentListener)
{
mListener = (OnCardsFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnCheeseCategoriesFragmentListener");
}
}
private void setUpLinearLayout()
{
linearLayout = (LinearLayout) view.findViewById(R.id.fragCards_LL);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new NestedScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void setUpCityFolders()
{
if(!Global_Class.getInstance().getValue().cityFoldersArrayList.isEmpty())
{
cityFolders = Global_Class.getInstance().getValue().cityFoldersArrayList;
for(CityFolders cityFolder : cityFolders)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(64,64,64,64);
lp.height = 200;//180dp = 720pixels
lp.width = 1408;//330dp = 1320 pixels.
CardView cityCardView = new CardView(getActivity());// ERROR
cityCardView.setBackgroundColor(000000);
cityCardView.setLayoutParams(lp);
linearLayout.addView(cityCardView, 0);
}
}
}
public interface OnCardsFragmentListener
{
void disableCollapse();
}
}
So, don't know what I am doing wrong here... hope someone can help, maybe point out what im doing wrong?
Also, in my cardView, going horizontally, I want to have an imageview, then a textview, followed by another textview. How would I inflate those parts of the cardView and fill them with an image, and 2 texts from my cityFolder object? Hope you guys can help me with an answer!
Cheers
EDIT:
So i implemented a recycler view and..nothing shows up on the screen... This recycler view just holds simple views with each view having an imageview and a textview, and nothing shows up..
<?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:paddingTop="24dp"
android:id="#+id/fragCards_LL">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragCards_RecyclerView">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here is my xml code for the view for each item in the recycler view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/fullstar"
android:id="#+id/fragCardsCity_imageview"
android:layout_gravity="center_vertical"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Star City"
android:layout_gravity="center_vertical"
android:id="#+id/fragCardsCity_textView"
android:padding="8dp"/>
</LinearLayout>
And finally, here is my java code.
public class FragmentCards extends Fragment
{
private ArrayList<CityFolders> cityFolders = new ArrayList<>();
private LinearLayout linearLayout;
private View rootView;
private RecyclerView recyclerView;
private CityViewAdapter cityAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_cards, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.fragCards_LL);
recyclerView = (RecyclerView) rootView.findViewById(R.id.fragCards_RecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
cityAdapter = new CityViewAdapter(getActivity(),getData());
recyclerView.setAdapter(cityAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
public static ArrayList<myData> getData()
{
ArrayList<myData> data = new ArrayList<>();
int[] icons = {R.drawable.fullstar,R.drawable.fullstar,R.drawable.fullstar,R.drawable.fullstar};
String[] titles = {"San Francisco","Seattle","Tokyo","Osaka"};
for(int i = 0; i < titles.length && i < icons.length; i++)
{
myData current = new myData();
current.iconId = icons[i];
current.cityName = titles[i];
data.add(current);
}
return data;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private static class myData
{
private int iconId;
private String cityName;
}
private class CityViewAdapter extends RecyclerView.Adapter<CityViewAdapter.MyViewHolder>
{
private LayoutInflater inflater;
private ArrayList<myData> infoList = new ArrayList<>();
public CityViewAdapter(Context context, ArrayList<myData> data)
{
inflater = LayoutInflater.from(context);
this.infoList = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = inflater.inflate(R.layout.fragment_cards_cityview,parent,false);
MyViewHolder holder = new MyViewHolder(view);//special way to avoid "findViewById everytime you make a view
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position)
{
myData current = infoList.get(position);
holder.title.setText(current.cityName);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView title;
ImageView icon;
public MyViewHolder(View itemView)
{
super(itemView);
title = (TextView) itemView.findViewById(R.id.fragCardsCity_textView);
icon = (ImageView) itemView.findViewById(R.id.fragCardsCity_imageview);
}
}
}
}

Categories

Resources