NullPointerException while using setText inside onBindViewHolder - android-recyclerview

I'm getting NullPointerException while using setText() inside OnBindViewHolder() while implementing recyclerview. I've debugged the entire code but not getting the solution. Please Explain why the 'holder.articleName' is thrown as null object?
Adapter Class:
public class ArticleListAdapter extends RecyclerView.Adapter<ArticleItemViewHolder> {
String[] articles = {
"article1",
"article2",
"article3",
"article4",
"article5"
};
#NonNull
#Override
public ArticleItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_article_list, parent, false);
return new ArticleItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ArticleItemViewHolder holder, final int position) {
holder.articleName.setText(articles[position]);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ArticleListActivity.this, "Article Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return articles.length;
}
}
ViewHolder Class:
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ArticleItemViewHolder extends RecyclerView.ViewHolder{
TextView articleName;
CardView cardView;
public ArticleItemViewHolder(View itemView) {
super(itemView);
this.articleName = itemView.findViewById(R.id.articleName);
this.cardView = itemView.findViewById(R.id.cardView);
}
}

Make sure the layout which has the TextView articleName is in the Layout page referenced here R.layout.activity_article_list and not any other layout page!

Related

Recycler view lost after fragment replacement

I have a single activity which replaces a fragment containing a recycler view with a fragment containing details of the selected viewholder item. When the back button is pressed the fragment containing the recycler view is restored but the recycler view items are no longer displayed. However, views are restored upon device rotation. All model data is stored in a SQLite database and the adapter list is updated on resume of its fragment .
CrimeListFragment.Java
public class CrimeListFragment extends Fragment {
private Callbacks callbacks;
public interface Callbacks {
public void onItemSelected(UUID id);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
callbacks = (Callbacks) context;
}
#Override
public void onDetach() {
super.onDetach();
callbacks = null;
}
private RecyclerView crimeListRecycler;
private CrimeListAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
crimeListRecycler = view.findViewById(R.id.crime_list);
crimeListRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.show_subtitle);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
/*Intent intent = CrimeActivity.createIntent(getActivity(), crime.getId());
startActivity(intent);*/
callbacks.onItemSelected(crime.getId());
return true;
default:
return onOptionsItemSelected(item);
}
}
private void updateUI() {
List<Crime> crimes = CrimeLab.get(getActivity()).getCrimes();
if (adapter == null) {
adapter = new CrimeListAdapter(crimes);
crimeListRecycler.setAdapter(adapter);
} else {
adapter.setCrimesList(crimes);
adapter.notifyDataSetChanged();
}
}
public class CrimeListAdapter extends RecyclerView.Adapter<CrimeListAdapter.CrimeHolder> {
private List<Crime> crimeList;
public CrimeListAdapter(List<Crime> crimes) {
crimeList = crimes;
}
#NonNull
#Override
public CrimeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_crime, parent, false);
return new CrimeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CrimeHolder holder, int position) {
Crime crime = crimeList.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return crimeList.size();
}
public void setCrimesList(List<Crime> crimes) {
crimeList = crimes;
}
public class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime crime;
private TextView crimeTitleTextView;
private TextView crimeDateTextView;
public CrimeHolder(#NonNull View itemView) {
super(itemView);
crimeTitleTextView = itemView.findViewById(R.id.crime_title);
crimeDateTextView = itemView.findViewById(R.id.crime_date);
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
this.crime = crime;
crimeTitleTextView.setText(crime.getTitle());
crimeDateTextView.setText(crime.getDate().toString());
}
#Override
public void onClick(View v) {
callbacks.onItemSelected(crime.getId());
/*Intent intent = CrimeActivity.createIntent(getActivity(), crime.getId());
startActivity(intent);*/
}
}
}
}
MasterActivity
public class MasterActivity extends AppCompatActivity implements CrimeListFragment.Callbacks {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new CrimeListFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
#Override
public void onItemSelected(UUID id) {
Fragment fragment = CrimeFragment.newInstance(id);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
}
Please share your code. Something to check when you replace/add your fragment on top of recyclerview fragment.

how fix NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
im new in android programing and i want to add JSON to my recyclerview i was getting the adapter not attetched skiping layout but my CustomAdapter is giving me NullPointerException too.
my CustomAdapter
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private List<RetroProduct> dataList;
private Context context;
CustomAdapter(Context context, List< RetroProduct > dataList){
this.context = context;
this.dataList = dataList;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
final View mView;
TextView goodsId,categoryTitle,number,title1,title2;
CustomViewHolder(View itemView) {
super(itemView);
mView = itemView;
goodsId = mView.findViewById(R.id.tv_goodsId);
categoryTitle = mView.findViewById(R.id.tv_categoryTitle);
number = mView.findViewById(R.id.tv_number);
title1 = mView.findViewById(R.id.tv_title1);
title2 = mView.findViewById(R.id.tv_title2);
}
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.item_row, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.goodsId.setText(dataList.get(position).getGoodsId());
holder.categoryTitle.setText(dataList.get(position).getCategoryTitle());
holder.title1.setText(dataList.get(position).getTitle1());
holder.title2.setText(dataList.get(position).getTitle2());
holder.number.setText(dataList.get(position).getNumber());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
and im getting NullPointerException on
return dataList.size();
what should i do now? give it value or i dont know.
MainActivity
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataService service =
RetrofitClientInstance.getRetrofitInstance()
.create(GetDataService.class);
Call< List<RetroProduct> > call = service.getAllProducts();
call.enqueue(new Callback<List<RetroProduct>>() {
#Override
public void onResponse(Call<List<RetroProduct>> call,
Response<List<RetroProduct>> response) {
generateDataList(response.body());
LinearLayoutManager manager = new
LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<RetroProduct>> call, Throwable t)
{
Toast.makeText(MainActivity.this, "null",
Toast.LENGTH_SHORT).show();
}
});
}
private void generateDataList(List<RetroProduct> productList) {
recyclerView = findViewById(R.id.recycler_view);
adapter = new CustomAdapter(this,productList);
}
}
#Override
public int getItemCount() {
if(dataList!=null)
return dataList.size();
else
return 0;
}
Add a null check before calling size() method of a Arraylist as above

paging library not showing anything in recyclerview

i'm trying to load bunch of list from room database, with paging library, but somehow that i don't really understand, the list never shown up
i add a repository class between dao and viewmodel, not sure if its the problem but, i configure Paged.list and pagedlistbuilder in there
i've also try to put some breakpoint in pagedListAdapter, but it never called
DAO
#Query("SELECT * FROM DictIndonesia")
public abstract DataSource.Factory<Integer, DictIndonesia> getAllPaged();
REPOSITORY
public class DictRepository {
PagedList.Config pagedListConfid;
.....
public DictRepository(Application application) {
db = DictIndoDatabase.getINSTANCE(application);
indDao = db.dictIdDao();
.....
pagedListConfid = (new PagedList.Config.Builder()
.setEnablePlaceholders(true)
.setPrefetchDistance(10)
.setPageSize(20).build());
}
......
public LiveData<PagedList<DictIndonesia>> getAllWordPaged() {
return new LivePagedListBuilder<>(
indDao.getAllPaged(), pagedListConfid).build();
}
viewmodel
public LiveData<PagedList<DictIndonesia>> getAllWordPaged() {
return dictRepository.getAllWordPaged();
}
ADAPTER
public class WordIndAdapterPaged extends PagedListAdapter<DictIndonesia,WordIndAdapterPaged.WordHolder> {
public WordIndAdapterPaged() {
super(diffcallBack);
}
#NonNull
#Override
public WordHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler, parent, false);
return new WordHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull WordHolder holder, int position) {
holder.bindTo(getItem(position));
}
private static final DiffUtil.ItemCallback<DictIndonesia> diffcallBack = new DiffUtil.ItemCallback<DictIndonesia>() {
#Override
public boolean areItemsTheSame(#NonNull DictIndonesia oldItem, #NonNull DictIndonesia newItem) {
return oldItem.getIdIndo() == newItem.getIdIndo();
}
#Override
public boolean areContentsTheSame(DictIndonesia oldItem, #NonNull DictIndonesia newItem) {
return oldItem == newItem;
}
};
public class WordHolder extends RecyclerView.ViewHolder {
...............
WordHolder(View view) {
super(view);
...............
}
void bindTo(DictIndonesia dictIndonesia) {
word.setText(Html.fromHtml(dictIndonesia.getWord()));
meaning.setText(Html.fromHtml(dictIndonesia.getMeaning()));
}
}
Fragment
public class Fdashboard extends Fragment {
#BindView(R.id.rv_global)
RecyclerView rvGlobal;
private Unbinder unbinder;
WordIndAdapterPaged wordIndAdapterPaged;
private WordViewModel wordViewModel;
public Fdashboard() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fdashboard, container, false);
unbinder = ButterKnife.bind(this, v);
wordViewModel = ViewModelProviders.of(getActivity()).get(WordViewModel.class);
wordIndAdapterPaged = new WordIndAdapterPaged();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rvGlobal.setLayoutManager(layoutManager);
rvGlobal.setAdapter(wordIndAdapterPaged);
wordViewModel.getAllWordPaged().observe(this, dictIndonesias -> {
wordIndAdapterPaged.submitList(dictIndonesias); //i think the problem maybe around here
});
return v;
}

How to play the song when an item is clicked in recyclerView (no buttons)?

I am creating a music app and I have listed my songs in RecyclerView. What I want is when I click any song(inside the red marked area), the song should play, just like in modern music players. I don't want any play, stop buttons on my RecyclerView. Any help would be appreciated! Thanks in advance!
Songs.java
public class Songs extends Fragment {
private static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
SongInfoModel s;
private MediaPlayer mediaPlayer;
ScaleInAnimationAdapter alphaAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_activity, container, false);
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
mediaPlayer = new MediaPlayer();
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
SongInfoModel s= new SongInfoModel("Cheap Thrills","Sia",null, null,
"http://mp3fb.com/wp-includes/inc/down.php?
id=hyCQomZzosfGBvVON0tRV7xfiL2GdtKXbTsBrZh_3NM&t=Sia%2B-
%2BCheap%2BThrils%2B%D0%A0%D0%B5%D0%BC%D0%B8%D0%BA%D1%81.mp3
&hash=true",null,null);
SongList.add(s);
songAdapter = new SongAdapter(getContext(),SongList);
alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
alphaAdapter.setDuration(1000);
alphaAdapter.setInterpolator(new OvershootInterpolator());
alphaAdapter.setFirstOnly(false);
recyclerView.setAdapter(alphaAdapter);
Collections.sort(SongList, new Comparator<SongInfoModel>(){
public int compare(SongInfoModel a, SongInfoModel b){
return a.getSongName().compareTo(b.getSongName());
}
});
return view;
}
SongAdapter.java:
public class SongAdapter extends
RecyclerView.Adapter<SongAdapter.SongHolder>
{
ArrayList<SongInfoModel> SongList = new ArrayList<>();
Context context;
MediaPlayer mediaPlayer;
SongInfoModel obj;
public SongAdapter(Context context, ArrayList<SongInfoModel> SongList) {
this.context = context;
this.SongList = SongList;
}
#Override
public SongAdapter.SongHolder onCreateViewHolder(ViewGroup parent, int
viewType)
{
View view = LayoutInflater.from(context).inflate(R.layout.row_song,
parent, false);
return new SongHolder(view);
}
#Override
public void onBindViewHolder(final SongAdapter.SongHolder holder, final
int
position) {
final SongInfoModel songInfoModel = SongList.get(position);
holder.songName.setText(songInfoModel.SongName);
holder.artistName.setText(songInfoModel.ArtistName);
}
#Override
public int getItemCount() {
return SongList.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView songName;
TextView artistName;
TextView duration;
public SongHolder(View itemView) {
super(itemView);
songName = (TextView)itemView.findViewById(R.id.SongName);
artistName= (TextView)itemView.findViewById(R.id.ArtistName);
duration = itemView.findViewById(R.id.duration);
}
}
}
First, Create an Interface in Adapter class like this -
private CustomOnClickListener customOnClickListener;
public interface CustomOnClickListener{
void onClick(int position);
}
After that Implement View.OnClickListener in View holder class
class TracksViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TracksViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
customOnClickListener.onClick(getAdapterPosition());
}
After that Implement CustomOnClickListener in your Fragment or Activity class.

android only show first viewpager inside recyclerview

i have a viewpager with FragmentStatePagerAdapter inside recyclerview
and its show only the first row in recyclerview
please help me
viewpager adapter:
public class CustomPagerAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
public CustomPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
Log.e("fragmentManager",fragmentManager.toString());
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
Fragment currentFragment;
switch (position) {
case 0:
currentFragment=new FirstFragment();
break;
case 1:
currentFragment=new SecondFragment();
break;
case 2:
currentFragment=new ThirdFragment();
break;
default:
currentFragment=new FirstFragment();
break;
}
return currentFragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
recyclerview adapter:
public class JobAdapter extends RecyclerView.Adapter<JobAdapter.JobHolder> {
private Context context;
private List<String> mJobList = new ArrayList<>();
public JobAdapter(List<String> mJobList,Context context) {
this.mJobList = mJobList;
this.context=context;
}
#Override
public JobHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.find_job_line_content, parent, false);
return new JobHolder(view);
}
#Override
public void onBindViewHolder(final JobHolder holder, int position) {
configurePagerHolder(holder, position);
}
private void configurePagerHolder(JobHolder holder, int position) {
//Job job= mJobList.get(position);
CustomPagerAdapter adapter = new CustomPagerAdapter(((MainActivity)context).getSupportFragmentManager());
holder.viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
holder.viewPager.setCurrentItem(1);
Log.e("configurePagerHolder",position+"");
}
public int getItemCount() {``
return mJobList.size();
}
public class JobHolder extends RecyclerView.ViewHolder{
ViewPager viewPager;
public JobHolder(View itemView) {
super(itemView);
viewPager=(ViewPager)itemView.findViewById(R.id.slidesPager);
}
}
main:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
JobAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView)findViewById(R.id.find_jobs_recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
List<String> list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
adapter = new JobAdapter(list,this);
mRecyclerView.setAdapter(adapter);
}
}
Very late answer but it might help some people...
Try using ViewPager2 ( an improved version of ViewPager) : https://developer.android.com/training/animation/screen-slide-2
In my case it solved the problem.