Data not shown in RecyclerView - java

I am trying to make a list of items with a Recycler View in a simple way by making a method called Data() that's has a for loop to set the text view continuously but when I run the app it show's me a white screen without anything.
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
RecyclerAdapter mAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView =(RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private class RecyclerAdapter extends RecyclerView.Adapter<MyViewHolder{
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item,parent,false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.Data();
}
#Override
public int getItemCount() {
return 100;
}
}
private class MyViewHolder extends RecyclerView.ViewHolder{
public TextView mmTextView ;
private Button mButton;
public MyViewHolder(View itemView) {
super(itemView);
mmTextView = (TextView) findViewById(R.id.list_text_view);
mButton = (Button) findViewById(R.id.list_button);
}
private void Data (){
for (int i =0 ;i<=100;i++){
mmTextView.setText(String.valueOf("Text : " + i));
}
}
}
}

You should infilate mmTextView from itemView not from Activity. It should be mmTextView = (TextView) itemView.findViewById(R.id.list_text_view);, also since it's a view of holder you can get it in onBindViewHolder() method using holder.mmTextView.setText(). Infilate button on onCreate() of Activity, also it's convenient to pass data to an adapter inside it's constructor and bind data to adapter on onBindViewHolder() method since it knows which views it possesses.

In onBindViewHolder method bind the data into the textView:
mmTextView.mmTextView.setText("SOME STRING VALUE");

Related

java.lang.NullPointerException with RecyclerView and CardView

I am trying to make dynamical list using RecyclerView and CardView using tutorial from this site and I am getting this error:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at kawi15.myapplication.CustomAdapter.getItemCount(CustomAdapter.java:66)
I run debugger to check that I have results from tmbd API and this is what I received:
http://prntscr.com/vdjj1h
This is my Fragment class activity when I want to create that list:
public class FragmentOne extends Fragment {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static List<MovieDb> data;
static View.OnClickListener myOnClickListener;
public static FragmentOne newInstance() {
FragmentOne fragment = new FragmentOne();
return fragment;
}
public class MovieTask extends AsyncTask<Void, Void, List<MovieDb>> {
#Override
protected List<MovieDb> doInBackground(Void... voids) {
MovieResultsPage movies = new TmdbApi("f753872c7aa5c000e0f46a4ea6fc49b2").getMovies().getUpcoming("en-US", 1, "US");
List<MovieDb> listMovies = movies.getResults();
return listMovies;
}
#Override
protected void onPostExecute(List<MovieDb> movieDb) {
data = movieDb;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
MovieTask mt = new MovieTask();
mt.execute();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
recyclerView = (RecyclerView) returnView.findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext()); // ???
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
return returnView;
}
}
and my Adapter class:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private List<MovieDb> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewVersion;
ImageView imageViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.text1);
this.textViewVersion = (TextView) itemView.findViewById(R.id.text2);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public CustomAdapter(List<MovieDb> data) {
this.dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
//view.setOnClickListener(MainActivity.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
ImageView imageView = holder.imageViewIcon;
Glide.with(imageView).load("http://image.tmdb.org/t/p/w500" + dataSet.get(listPosition).getPosterPath()).into(imageView);
textViewName.setText(dataSet.get(listPosition).getOriginalTitle());
textViewVersion.setText(dataSet.get(listPosition).getReleaseDate());
//imageView.setImageResource(dataSet.get(listPosition).);
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
I stucked with my code with this and I dont have idea where is mistake.
Initially dataSet is null. So using dataSet.size() is throwing NullPointerException.
Change getItemCount method in the following way.
#Override
public int getItemCount() {
if(dataSet == null){
return 0;
}
return dataSet.size();
}
This is removing error but its still doesnt work because data is null making dataSet null too. I dont know why data is null, I need help with this.
Reason for that could be, you are creating CustomAdapter object in onCreateView method, which is kind of called before you AsyncTask has finished. So, when onCreateView is being called, data is null.
To fix it, You can add a setter method in your CustomAdapter, which will allow you to update dataSet, even after the adapter object is created. Then you will have to update the dataSet in your onPostExecute method & after that use notifyDataSetChanged on the adapter, to reflect the changes.
At the start dataSet will be null until you assign it a value, and then feed it back with data, so change getItemCount() to below to return 0 data when it's null
#Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
}
Ok, there is no error and application is launching but still I dont have list and this is my problem
You need to update the changes to your adapter with notifyDataSetChanged()
#Override
protected void onPostExecute(List<MovieDb> movieDb) {
data = movieDb;
adapter.notifyDataSetChanged();
}
Now two possible things, either TmdbApi("...").getMovies() doesn't really return data, in this case you need to debug it and check if it returns data or not.
The other thing, move the code of the AsyncTask execution after creating the RecyclerView instance in onCreateView and Initialize the adapter in onPostExecute();
Here are after the changes:
public class MovieTask extends AsyncTask<Void, Void, List<MovieDb>> {
#Override
protected List<MovieDb> doInBackground(Void... voids) {
MovieResultsPage movies = new TmdbApi("f753872c7aa5c000e0f46a4ea6fc49b2").getMovies().getUpcoming("en-US", 1, "US");
List<MovieDb> listMovies = movies.getResults();
return listMovies;
}
#Override
protected void onPostExecute(List<MovieDb> movieDb) {
data = movieDb;
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
recyclerView = (RecyclerView) returnView.findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext()); // ???
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
MovieTask mt = new MovieTask();
mt.execute();
return returnView;
}

How do i add the show more functionality to getting firebase database?

I am new in firebase android app development.
In this app i fetched the data from firebase database.
Here i want to implement show more functionality in recyclerview to save data loading.
I see the solution in many stackoverflow question. But in every question The adapter class is defined outside from main activity. so i cant understand properly.
And here my adapter is within main activty class.
class MainActivity extends AppCompatActivity {
private RecyclerView postList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PostRef=FirebaseDatabase.getInstance().getReference().child("Posts");
postList = (RecyclerView) findViewById(R.id.all_user_post_list);
postList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
postList.setLayoutManager(linearLayoutManager);
displayAllUserPost();
}
private void displayAllUserPost() {
Query sortPost=PostRef;
FirebaseRecyclerOptions<Post> options=new FirebaseRecyclerOptions.Builder<Post>().setQuery(sortPost,Post.class).build();
FirebaseRecyclerAdapter<Post, PostsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Post, PostsViewHolder>(options)
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, final int position, #NonNull final Post model) {
final String PostKey = getRef(position).getKey();
holder.postfullname.setText(model.getFirstname() + " " + model.getLastname());
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.all_post_layout,parent,false);
PostsViewHolder viewHolder=new PostsViewHolder(view);
return viewHolder;
}
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder
{
TextView postfullname;
public PostsViewHolder(View itemView)
{
super(itemView);
postfullname = itemView.findViewById(R.id.user_post_full_name);
}
}
}
So How i add show more functionality in this code when first load only 10 items and than after load more 10 items with rounded progressbar(show more button is not important).
Most important thing is that first load only 10 items. rest item should not be loaded until user scrolled down to last(10th) item
Thank you.

Recyclerview in fragment inside a viewpager

I wanted to use recyclerview inside a fragment of my 3 fragment viewpager. I wrote the code and it ran perfectly but I don't know why it is too slow.When I swap from one fragment to another it almost takes half minute.Don't know what mistakes I did here.
Main Activity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.toolBar);
tabLayout = (TabLayout)findViewById(R.id.tabs);
viewPager = (ViewPager)findViewById(R.id.viewPager);
setSupportActionBar(toolbar);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(new OneFragment(), "One");
viewPagerAdapter.addFragment(new TwoFragment(), "Two");
viewPagerAdapter.addFragment(new ThreeFragment(), "Three");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
Here it is one of my fragment where I tried to implement recyclerview.
Fragment
public class TwoFragment extends Fragment {
public TwoFragment() {
// 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_two, container, false);
OurData ourData = new OurData();
ourData.pic.add(R.drawable.b);
ourData.title.add("Hello");
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.listRecyclerView);
ListAdapter listAdapter = new ListAdapter();
recyclerView.setAdapter((listAdapter));
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
public class ListAdapter extends RecyclerView.Adapter {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((ListViewHolder) holder).bindView(position);
}
#Override
public int getItemCount() {
return OurData.title.size();
}
private class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView text;
private ImageView image;
public ListViewHolder(View itemview) {
super(itemview);
text = (TextView) itemview.findViewById(R.id.textF);
image = (ImageView) itemview.findViewById(R.id.imageF);
itemview.setOnClickListener(this);
}
public void bindView(int position) {
text.setText(OurData.title.get(position));
image.setImageResource(OurData.pic.get(position));
}
public void onClick(View view) {
}
}
}
public class OurData {
public static ArrayList<String> title = new ArrayList<String>();
public static ArrayList<Integer> pic = new ArrayList<Integer>();
}
It tooks my whole day thinking what I did wrong. Please help me out!
set your adapter recyclerView.setAdapter((listAdapter));
insise onViewCreated instead of onCreateView
I think the problem is because of one of your Methods.
maybe 'OurData'
and also are you sure of this:
#Override
public int getItemCount() {
return OurData.title.size();
}
also try using Log in each code and see the part that takes time especially 'OurData'

Integrating recyclerview with database

#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
Collections.swap(queuee, viewHolder.getAdapterPosition(), target.getAdapterPosition());
// and notify the adapter that its dataset has changed
adapterr.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
With the above code i m able to swap the items in the recyclerview ,but now the problem is i also want to make the same respective changes to database.
How to go about?
queuee receives the all the data from the database
queuee is a arraylist which is used to set the recyclerview adapter
Regards
Thanks
Adapter:
public class QueueAdapter extends RecyclerView.Adapter<QueueAdapter.MyViewHolder> {
private Context mContext;
public ArrayList<Music> queue;
MediaPlayer mPlayer = new MediaPlayer();
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title,tt,artist;
public Button play,stop;
public ImageButton option;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.songtitle1);
artist = (TextView)view.findViewById(R.id.artist1);
// play = (Button) view.findViewById(R.id.play);
// stop = (Button) view.findViewById(R.id.stop);
// tt = (TextView) view.findViewById(R.id.song_name);
option = (ImageButton) view.findViewById(R.id.option1);
}
}
public QueueAdapter(Context mContext, ArrayList<Music> queue) {
this.mContext = mContext;
this.queue = queue;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.queue_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Music mu1 = queue.get(position);
holder.title.setText(mu1.getTitle());
holder.artist.setText(mu1.getArtist());
final String link =mu1.getUrl();
final String SongName = mu1.getTitle();
}
#Override
public int getItemCount() {
return queue.size();
}
public void removeItem(int position) {
queue.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, queue.size());
}
}
activity:
recyclerView = (RecyclerView) findViewById(R.id.recyclerqueue);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapterr = new QueueAdapter(this,queuee);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
// adapterr.
recyclerView.setAdapter(adapterr);
initSwipe();
In my opinion, you can do it on OnDestroy method in your Activity. Specifically speaking, firstly, you can get all your data from your adapter, and then delete datas in your database, at last, you can save your data obtained from your adapter again. In this moment, the sequence of your datas is what you want, and this way is easy to code. I'd rather you don't
update your database during onMove, because it's too frequently during your drag, and operates all data is easier than two datas in database.

Android: Open a Dialog by clicking on programatically added views into a RecyclerView

What I have: a button that when clicked adds a custom view (a button, a textView and an EditText) into a recyclerView. When the button inside some view gets clicked that view gets removed.
What I want: a button that when clicked adds a custom view (a button, a TextView and an EditText) into a RecyclerView. When a button inside some view gets clicked, a DialogFragment shows.
I guess I could do that inside the Adapter but that feels like it would mess up with the whole project architecture, so I need a way to do it in my activity class.
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> items = new ArrayList<>();
public void addItem(String name) {
items.add(name);
notifyItemInserted(items.size() - 1);
}
public void removeItem(int position) {
items.remove(position);
notifyItemRemoved(position);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.grid_item_button, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return items.size();
}
static int i;
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button button;
private TextView ClassName;
private EditText EditName;
public ViewHolder(View itemView) {
super(itemView);
ClassName = (TextView) itemView.findViewById(R.id.ClassName);
button = (Button) itemView.findViewById(R.id.grid_button);
EditName = (EditText) itemView.findViewById(R.id.editName);
button.setOnClickListener(this);
ClassName.setId(++i);
EditName.requestFocus();
}
#Override
public void onClick(View v) {
removeItem(getAdapterPosition());
}
}
}
Main activity's onCreate
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ClassesRecyclerView);
assert recyclerView != null;
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
final MyAdapter adapter = new MyAdapter();
recyclerView.addItemDecoration(new SampleItemDecoration());
recyclerView.setAdapter(adapter);
recyclerView.setNestedScrollingEnabled(false);
adapter.addItem("");
findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.addItem("");
}
});

Categories

Resources