My views are giving me a null pointer exception - android

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.

Related

I can't scroll the recyclerView of one fragment

I have 6 fragments in a Sliding tab layout. All of them have RecyclerView implemented in them. I have populated the RecyclerView. But I one of the fragments does not allow me to scroll, but the rest are working fine.
See the gif below:
This is my problem
Genres.java
public class Genres extends Fragment {
private static final String TAG = "Genres";
RecyclerView recyclerView_genre;
GenresAdapter genresAdapter;
ArrayList<GenresModel> Genrelist = new ArrayList<>();
long genreId;
String genreName;
Cursor genrecursor;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.genres_activity, container, false);
recyclerView_genre = view.findViewById(R.id.recyclerView_genre);
recyclerView_genre.setHasFixedSize(true);
LinearLayoutManager genreLayout = new LinearLayoutManager(getContext());
recyclerView_genre.setLayoutManager(genreLayout);
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
genrecursor=getActivity().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,proj1,null, null, null);
if (genrecursor != null) {
if (genrecursor.moveToFirst()) {
do {
genreId = genrecursor.getLong(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID));
genreName = genrecursor.getString(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME));
GenresModel genresModel = new GenresModel(genreId,genreName );
Genrelist.add(genresModel);
Collections.sort(Genrelist, new Comparator<GenresModel>() {
#Override
public int compare(GenresModel lhs, GenresModel rhs) {
return lhs.getGenreName().compareTo(rhs.getGenreName());
}
});
} while (genrecursor.moveToNext());
}
}
genrecursor.close();
genresAdapter = new GenresAdapter(getContext(),Genrelist);
recyclerView_genre.setAdapter(genresAdapter);
genresAdapter.notifyDataSetChanged();
return view;
}
GenresAdapter.java
public class GenresAdapter extends RecyclerView.Adapter<GenresAdapter.GenresHolder> {
Context gContext;
ArrayList<GenresModel> GenreList = new ArrayList<>();
public GenresAdapter(Context gContext, ArrayList<GenresModel> genreList) {
this.gContext = gContext;
GenreList = genreList;
}
#Override
public GenresAdapter.GenresHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view3 = LayoutInflater.from(gContext).inflate(R.layout.row_genre, parent, false);
return new GenresHolder(view3);
}
#Override
public void onBindViewHolder(GenresAdapter.GenresHolder holder, int position) {
final GenresModel genresModel1 = GenreList.get(position);
holder.genreText.setText( genresModel1.getGenreName());
}
#Override
public int getItemCount() {
return GenreList.size();
}
public class GenresHolder extends RecyclerView.ViewHolder {
TextView genreText;
public GenresHolder(View itemView) {
super(itemView);
genreText = itemView.findViewById(R.id.genreText);
}
}
}
activity_genre.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.support.v7.widget.RecyclerView
android:id="#+id/recyclerView_genre"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="130dp"
>
</android.support.v7.widget.RecyclerView>
</LinearLayout>
row_genre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:paddingTop="35dp"
>
<TextView
android:id="#+id/genreText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="14sp"
/>
</LinearLayout>
I found out the solution myself. Actually the the problem was with the viewpager transformation. I applied https://github.com/geftimov/android-viewpager-transformers/wiki/CubeOutTransformer to my viewpager and for some reason my first 3 fragments were working and rest were not!

Loading images from the custom video gallery

I'm working on a page in which I have a button which takes you to the video gallery which I have created. From this you select some videos(thumbnails) and then hit the arrow to come back to the same place from where I hit the button to come to the Custom gallery with the selected videos.
Basically the map goes like this :
Button(from AddFragment)->VideoGallery->Select videos-> AddFragment with selected videos which is visible inside the recycler view
Now when I hit the button I come to my videogallery but when I select some videos from the gallery and come back to the AddFragment it shows nothing and one error comes up that is E/RecyclerView: No adapter attached; skipping layout
Now I have used Bundle to extract the sent data and populate it in my AddFragment.
I'm giving out the code for you :
1. AddFragment.java
public class AddFragment extends Fragment {
private ImageButton nextActivity;
private RecyclerView recyclerView;
private ProgressDialog videoProgressDialog;
ArrayList<File> checkedList = new ArrayList<>();
ImageAdapter imageAdapter;
Button button;
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
nextActivity = (ImageButton) view.findViewById(R.id.gotoButton);
recyclerView = (RecyclerView) view.findViewById(R.id.grid_add_view);
button = (Button) view.findViewById(R.id.buttonToGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(),VideoGalleryActivity.class));
}
});
return view;
}
//making adapter for RecyclerView which loads the desired files
class ImageAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mInflater;
private Bitmap bitmap;
private ArrayList<File> fileName;
public ImageAdapter(ArrayList<File> checkedList) {
fileName = checkedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue){
File filePath = new File(pathName);
checkedList.add(filePath);
}
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
View items = mInflater.from(parent.getContext()).inflate(R.layout.custom_added_video,
parent,false);
items.setLayoutParams(new AbsListView.LayoutParams(215,215));
return new ViewHolder(items);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(fileName != null){
bitmap = ThumbnailUtils.createVideoThumbnail(fileName.get(position).toString(),1);
holder.imageView.setImageBitmap(bitmap);
}
}
#Override
public int getItemCount() {
return fileName.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
//public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
//imageButton = (ImageButton) itemView.findViewById(R.id.addVideos);
imageView = (ImageView) itemView.findViewById(R.id.galleryImageView);
}
} }
2. fragment_add.xml
<LinearLayout 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:orientation="vertical"
android:background="#color/colorWhite"
tools:context="in.pinelane.myhovi.AddFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linearLayout"
android:padding="19dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textStyle="bold"
android:text="Choose Videos"
android:textColor="#color/colorBackground"/>
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<ImageButton
android:id="#+id/gotoButton"
android:layout_width="25sp"
android:layout_height="25sp"
android:background="#00ffffff"
android:src="#mipmap/ic_arrow_forward_black_24dp"/>
</LinearLayout>
<Button
android:id="#+id/buttonToGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/grid_add_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
Inflates this layout
custom_added_video.xml
<?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="wrap_content"
android:background="#color/colorWhite"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_marginEnd="3dp"
android:layout_marginStart="3dp">
<!--<ImageButton-->
<!--android:id="#+id/addVideos"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:src="#mipmap/ic_add_black_24dp"-->
<!--android:layout_margin="3dp"-->
<!--android:background="#drawable/edittext_border"-->
<!--android:layout_centerInParent="true"/>-->
<ImageView
android:id="#+id/galleryImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_margin="3dp"
android:layout_centerInParent="true"/>
Any idea would be of great help! Thanks
I've tried defining the below code in onCreate but I got a NullPointerException so I defined the same inside the onCreateViewHolder but no result just No Adapter attached; skipping layout
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue){
File filePath = new File(pathName);
checkedList.add(filePath);
}
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
EDITS
I've made some changes inside my code and user onActivityResult and startActivityForResult in this fragment but still no result. My AddFragment is still blank and not showing any result
Edited AddFragment.java
public class AddFragment extends Fragment {
private ImageButton nextActivity;
private RecyclerView recyclerView;
ArrayList<File> checkedList = new ArrayList<>();
ImageAdapter imageAdapter;
Button button;
private static final int CustomGallerySelectId = 1;//Set Intent Id
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
nextActivity = (ImageButton) view.findViewById(R.id.gotoButton);
recyclerView = (RecyclerView) view.findViewById(R.id.grid_add_view);
button = (Button) view.findViewById(R.id.buttonToGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(getContext(),VideoGalleryActivity.class),CustomGallerySelectId);
}
});
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
GridLayoutManager videoGrid = new GridLayoutManager(getContext(),3);
recyclerView.setLayoutManager(videoGrid);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case CustomGallerySelectId :
if(requestCode == RESULT_OK){
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue) {
File filePath = new File(pathName);
checkedList.add(filePath);
}
}
}
}
//making adapter for RecyclerView which loads the desired files
class ImageAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mInflater;
private Bitmap bitmap;
private ArrayList<File> fileName;
public ImageAdapter(ArrayList<File> checkedList) {
fileName = checkedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View items = mInflater.from(parent.getContext()).inflate(R.layout.custom_added_video,
parent,false);
items.setLayoutParams(new AbsListView.LayoutParams(215,215));
return new ViewHolder(items);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(fileName != null){
bitmap = ThumbnailUtils.createVideoThumbnail(fileName.get(position).toString(),1);
holder.imageView.setImageBitmap(bitmap);
}
}
#Override
public int getItemCount() {
return fileName.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
//public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
//imageButton = (ImageButton) itemView.findViewById(R.id.addVideos);
imageView = (ImageView) itemView.findViewById(R.id.galleryImageView);
}
} }
Move this code:
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
to your createView() method.
In createView you are inflating the layout, you are finding the RecyclerView but you are not setting an adapter to it. The RecyclerView doesn't have any data to show, so it's skipped from the layout for a performance boost. You should also set a LayoutManager. If you need a simple list, you should use LinearLayoutManager.
The createViewHolder() method is called once for each visible element of your RecyclerView. It's not the right place to perform the initial setup of your RecyclerView.

RecyclerView won't display my database content

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.

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.

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