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
Related
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.
I am very new to Android programming. I can't find a solution for my current problem which I've been trying to solve for days.
I want to click on item of populated Array List and get the position i.e. the searched word result in Cardview (neither ItemClickListener nor OnSuggestionListener did work here. Here is my code of MainActivity and I would be very thankful if somebody could help me out:
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//init View
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
database = new Database(this);
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener (new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for (String search : suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener (new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
adapter = new SearchAdapter(getBaseContext(), database.getLughats());
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
adapter = new SearchAdapter(this, database.getLughats());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this, database.getLughatByWort(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getWorts();
materialSearchBar.setLastSuggestions(suggestList);
}
}```
Let me know if I should post here also my AdapterCode for the ViewHolder.
Thank you for your help in advance!
Here ist my AdapterCode:
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RecyclerItemClick itemClickListener;
public TextView wort, praeteritum, partizip2, artikelGrammatik, uebersetzung1, uebersetzung2;
public ImageButton button1, button2;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
wort = (TextView)itemView.findViewById(R.id.wort);
praeteritum = (TextView)itemView.findViewById(R.id.praeteritum);
partizip2 = (TextView)itemView.findViewById(R.id.partizip2);
artikelGrammatik = (TextView)itemView.findViewById(R.id.artikelGrammatik);
uebersetzung1 = (TextView)itemView.findViewById(R.id.uebersetzung1);
uebersetzung2 = (TextView)itemView.findViewById(R.id.uebersetzung2);
button1 = (ImageButton)itemView.findViewById(R.id.button_id_1);
button2 = (ImageButton) itemView.findViewById(R.id.button_id_2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemClickListener(RecyclerItemClick ic) {
this.itemClickListener = ic;
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Lughat> lughats;
public SearchAdapter(Context context, List<Lughat> lughats) {
this.context = context;
this.lughats = lughats;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SearchViewHolder holder, final int position) {
holder.wort.setText(lughats.get(position).getWort());
holder.praeteritum.setText(lughats.get(position).getPraeteritum());
holder.partizip2.setText(lughats.get(position).getPartizip2());
holder.artikelGrammatik.setText(lughats.get(position).getArtikelGrammatik());
holder.uebersetzung1.setText(lughats.get(position).getUebersetzung1());
holder.uebersetzung2.setText(lughats.get(position).getUebersetzung2());
CharSequence praet;
praet = holder.praeteritum.getText();
if (praet.length() == 0) {
holder.praeteritum.setVisibility(View.GONE);
holder.button1.setVisibility(View.GONE);
} else {
holder.praeteritum.setVisibility(View.VISIBLE);
holder.button1.setVisibility(View.VISIBLE);
}
CharSequence part2;
part2 = holder.partizip2.getText();
if (part2.length() == 0) {
holder.partizip2.setVisibility(View.GONE);
} else {
holder.partizip2.setVisibility(View.VISIBLE);
}
CharSequence artGr;
artGr = holder.artikelGrammatik.getText();
if (artGr.length() == 0) {
holder.artikelGrammatik.setVisibility(View.GONE);
holder.button2.setVisibility(View.GONE);
} else {
holder.artikelGrammatik.setVisibility(View.VISIBLE);
holder.button2.setVisibility(View.VISIBLE);
}
CharSequence ueb2;
ueb2 = holder.uebersetzung2.getText();
if (ueb2.length() == 0) {
holder.uebersetzung2.setVisibility(View.GONE);
} else {
holder.uebersetzung2.setVisibility(View.VISIBLE);
}
holder.button1.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.button2.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.setItemClickListener(new RecyclerItemClick() {
#Override
public void onItemClickListener(View v, int position) {
Toast.makeText(context, "Begriff", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return lughats.size();
}
}
If I do it also with OnClickListener it does not work too, it does not call the method startSearch.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence text = materialSearchBar.getText();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
startSearch(text.toString());
}
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;
}
I have a recyclerview with a textview and the clicked textview gets a background around it.I also have a button within the activity which should put a background to all the items in the recyclerview ie..to show all selected.I am putting my activity and adapter code.please help me
my activity code
set_all_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommonUtility.selectedDays.clear();
CommonUtility.selectedDays.addAll(daysList);
//loadDays();
}
});
my adapter
public class DaysAdapter<T> extends RecyclerView.Adapter<DaysAdapter.ViewHolder> {
private ArrayList<String> list=new ArrayList<>();
private Context mContext;
private RecyclerViewClickListener mListener;
public DaysAdapter(ArrayList<String> data, Context context, RecyclerViewClickListener listener) {
list = data;
//languageListFiltered = filteredData;
mContext = context;
mListener = listener;
}
#Override
public void onBindViewHolder(DaysAdapter.ViewHolder viewHolder, final int position) {
viewHolder.titleTextView.setText(list.get(position));
// viewHolder.lang_radio.setChecked(position == mSelectedItem);
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mContext);
final View view = inflater.inflate(R.layout.days_list_item, viewGroup, false);
return new ViewHolder(view);
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ViewHolder(final View inflate) {
super(inflate);
titleTextView = (TextView)inflate.findViewById(R.id.text_day);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!CommonUtility.selectedDays.contains(titleTextView.getText().toString()))
{
titleTextView.setBackground(mContext.getResources().getDrawable(R.drawable.green_circle));
titleTextView.setTextColor(mContext.getResources().getColor(R.color.white));
CommonUtility.selectedDays.add(titleTextView.getText().toString());
Log.d("added",titleTextView.getText().toString());
}
else
{
int index=CommonUtility.selectedDays.indexOf(titleTextView.getText().toString());
CommonUtility.selectedDays.remove(index);
titleTextView.setBackground(null);
Log.d("removed",titleTextView.getText().toString());
titleTextView.setTextColor(mContext.getResources().getColor(R.color.black));
}
}
};
itemView.setOnClickListener(clickListener);
titleTextView.setOnClickListener(clickListener);
}
}
}
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.