How to getAdapterPositions without getting null in OnClick Adapter on View Holder? - android

I like to get the positions i try using simple toast and i got it, but when i try to using it for interface i got an error
ListActivity
public class ListActivity extends BaseActivity implements ListAdapter.OnClickListenerAdapterList {
private DatabaseReference databaseReference;
private RecyclerView labelRecycleView;
private ArrayList<DataFirebase> listLabel = new ArrayList<>();
private ListAdapter listAdapter;
private Button bInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
findView();
setDataToList();
initListener();
}
private void setDataToList() {
simpleway.progressDialog(ListActivity.this);
databaseReference.child("Username").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
DataFirebase modelClass = dataSnap.getValue(DataFirebase.class);
modelClass.setLabel(dataSnap.getKey());
listLabel.add(modelClass);
}
putLayoutManager();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println(databaseError.getDetails() + " " + databaseError.getMessage());
simpleway.stopProgressDialog();
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
labelRecycleView.setLayoutManager(layoutManager);
labelRecycleView.setItemAnimator(new DefaultItemAnimator());
}
private void putLayoutManager() {
listAdapter = new ListAdapter(ListActivity.this, listLabel, this);
labelRecycleView.setAdapter(listAdapter);
simpleway.stopProgressDialog();
}
#Override
public void findView() {
databaseReference = FirebaseDatabase.getInstance().getReference();
labelRecycleView = findViewById(R.id.listRecyclerVIew);
bInput = findViewById(R.id.inputData);
}
#Override
public void initListener() {
bInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
simpleway.startnextActivity(ListActivity.this, InputActivity.class);
}
});
}
#Override
public void OnClickPositionsAndValue(String enough) {
TitleFragment titleFragment = new TitleFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager()
.beginTransaction();
Bundle bundle = new Bundle();
bundle.putString("Check", enough);
titleFragment.setArguments(bundle);
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right,
R.anim.enter_from_right, R.anim.exit_to_right)
.replace(R.id.container_layout, titleFragment)
.addToBackStack(null)
.commit();
}
}
ListAdapter
public class ListAdapter extends RecyclerView.Adapter {
private Simpleway simpleway;
private ArrayList<DataFirebase> dataList;
private AppCompatActivity someActivity;
private Fragment fragmentActivity;
private OnClickListenerAdapterList onClickListenerAdapterList;
public ListAdapter(AppCompatActivity someActivity, ArrayList<DataFirebase> dataList,
OnClickListenerAdapterList onClickListenerAdapterList) {
this.dataList = dataList;
this.someActivity = someActivity;
simpleway = new Simpleway();
}
public ListAdapter(Fragment fragmentActivity, ArrayList<DataFirebase> dataList,
OnClickListenerAdapterList onClickListenerAdapterList) {
this.dataList = dataList;
this.fragmentActivity = fragmentActivity;
simpleway = new Simpleway();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_label, viewGroup, false);
return new ViewHolder(view, onClickListenerAdapterList);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int positions) {
final DataFirebase labelList = dataList.get(positions);
viewHolder.textLabel.setText(labelList.getLabel());
String enough = labelList.getLabel();
}
#Override
public int getItemCount() {
return dataList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
LinearLayout linearLabel;
TextView textLabel;
OnClickListenerAdapterList monClickListenerAdapterList;
ViewHolder(#NonNull View itemView, OnClickListenerAdapterList onClickListenerAdapterList) {
super(itemView);
textLabel = itemView.findViewById(R.id.text_label);
linearLabel = itemView.findViewById(R.id.linearLabel);
monClickListenerAdapterList = onClickListenerAdapterList;
linearLabel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
simpleway.toastMessage(someActivity.getApplicationContext(), String.valueOf(getAdapterPosition()));
monClickListenerAdapterList.OnClickPositionsAndValue(getAdapterPosition());
}
}
public interface OnClickListenerAdapterList{
void OnClickPositionsAndValue(int positions);
}
}
and mostly when i try to getAdapterPositions the error i got is like this.
The Error
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.parzival.flashcard.adapter.ListAdapter$OnClickListenerAdapterList.OnClickPositionsAndValue(int)' on a null object reference
at com.example.parzival.flashcard.adapter.ListAdapter$ViewHolder.onClick(ListAdapter.java:90)
how do i getAdapter positions? is there something wrong with my interface?

The problem appears to be that your monClickListenerAdapterList is just null.
If you look at the constructor of your ListAdapter class, you'll see:
public ListAdapter(AppCompatActivity someActivity, ArrayList<DataFirebase> dataList,
OnClickListenerAdapterList onClickListenerAdapterList) {
this.dataList = dataList;
this.someActivity = someActivity;
simpleway = new Simpleway();
}
However, notice that although you passed in OnClickListenerAdapterList onClickListenerAdapterList as a parameter, you never called this.onClickListenerAdapterList = onClickListenerAdapterList; inside the constructor.
As such, you're simply passing in the listener, but never storing it... so the ListAdapter's onClickListenerAdapterList is actually still null.
So when you pass in that onClickListenerAdapterList to your ViewHolders, you're actually passing in the onClickListenerAdapterList that's still null.
So to fix your error, simply change your constructor to be:
public ListAdapter(AppCompatActivity someActivity, ArrayList<DataFirebase> dataList,
OnClickListenerAdapterList onClickListenerAdapterList) {
this.dataList = dataList;
this.someActivity = someActivity;
this.onClickListenerAdapterList = onClickListenerAdapterList;
simpleway = new Simpleway();
}

Related

About opening a new activity in respond to a click on a RecyclerView item which is inside of a fragment

I'm loading some data into a RecyclerView from Firebase Realtime Database. This RecyclerView is in a fragment and I want to open a new activity when an item is clicked. But when i add the onClickListener to an item from the adapter, my click doesn't even recognized by the app. I'm not sure what I'm doing wrong here because this method worked fine for a RecyclerView when it is inside of a normal activity.
This is a project for my university and I should submit it tomorrow. So I can really use some help.
This is the my data Adapter class,
public class Adapter_NoLimit extends RecyclerView.Adapter<Adapter_NoLimit.LViewHolder> {
Context context;
ArrayList<Helper> list_nl;
public Adapter_NoLimit(Context context, ArrayList<Helper> list_nl) {
this.context = context;
this.list_nl = list_nl;
}
#NonNull
#Override
public Adapter_NoLimit.LViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.itemlist, parent, false);
return new LViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull Adapter_NoLimit.LViewHolder holder, int position) {
//final Helper temp = list_nl.get(position);
String fname_txt = list_nl.get(position).getFname();
String catg_txt = list_nl.get(position).getSpin();
String prof_img = list_nl.get(position).getProfile_url();
holder.setUsers(fname_txt, catg_txt, prof_img);
holder.f_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
Intent i = new Intent(activity, UserProfile_VV.class);
i.putExtra("full name", fname_txt);
activity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list_nl.size();
}
public class LViewHolder extends RecyclerView.ViewHolder{
private TextView f_name, catG;
private ImageView profile_pic;
public LViewHolder(#NonNull View itemView) {
super(itemView);
f_name = itemView.findViewById(R.id.username_view);
catG = itemView.findViewById(R.id.category_view);
profile_pic = itemView.findViewById(R.id.userimage);
}
public void setUsers(String fname_txt, String catg_txt, String prof_img) {
f_name.setText(fname_txt);
catG.setText(catg_txt);
Picasso.get().load(prof_img).fit().into(profile_pic);
}
}
}
This is one of fragments,
public class Beauty_Frag extends Fragment {
RecyclerView recyclerView;
DatabaseReference reference, user_ref;
ArrayList<Helper> list;
Adapter adapter;
FirebaseAuth auth;
String uid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_beauty, container, false);
recyclerView = v.findViewById(R.id.beauty_recycler_frag);
reference = FirebaseDatabase.getInstance().getReference();
user_ref = reference.child("users");
auth = FirebaseAuth.getInstance();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//searchField = findViewById(R.id.search_field);
list = new ArrayList<>();
adapter = new Adapter(getContext(), list);
recyclerView.setAdapter(adapter);
user_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull /*#org.jetbrains.annotations.NotNull*/ DataSnapshot snapshot) {
for (DataSnapshot key : snapshot.getChildren()) {
if( key.child("spin").getValue().toString().equals("Beauty")) {
Helper helper = key.getValue(Helper.class);
list.add(helper);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull /*#org.jetbrains.annotations.NotNull*/ DatabaseError error) {
}
});
return v;
}
}
You are very welcome if you have any solution.
Use below code for onClicklistner:
holder.f_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfile_VV.class);
i.putExtra("full name", fname_txt);
context.startActivity(i);
}
});

RecycerView always reset back to first position after inserting new Firebase data

My recyclerview always reset to first position after new data is inserted to firebase. In my TestAdapter class, I have an onClickListener which increments like on a post when clicked. Whenever I click on this "like" button, view is reset to first position. I believe this issue is related to setAdapter() being called on data changed. Please help!
MainActivity fetches "post" data from Firebase and populates it in TestAdapter class.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private TestAdapter testAdapter;
private ArrayList<Post> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
fetchPostFromDB();
}
private void fetchPostFromDB() {
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("Post");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postList = new ArrayList<>();
for (DataSnapshot snap : snapshot.getChildren()) {
String post = snap.child("post").getValue().toString();
Post post = new Post(post);
postList.add(post);
}
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
TestAdapter binds the data (postList) and has an onClickListener.
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestHolder> {
private List<Post> postList;
private Context context;
private DatabaseReference databaseReference;
public TestAdapter(Context ct, ArrayList<Post> postList) {
context = ct;
this.postList = postList;
}
#NonNull
#Override
public TestHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.post_item, parent, false);
final TestHolder holder = new TestHolder(view);
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
databaseReference.setValue(incrementLike);
}
});
return holder;
}
#Override
public void onBindViewHolder(#NonNull final TestHolder holder, final int position) {
holder.tvPost.setText(postList.get(position).getPost());
holder.tvVotes.setText(Integer.toString(postList.get(position).getLikes()));
}
#Override
public int getItemCount() {
return postList.size();
}
public static class TestHolder extends RecyclerView.ViewHolder {
TextView tvPost, tvLikes;
ImageButton ibLike;
public TestHolder(#NonNull View itemView) {
super(itemView);
tvPost = itemView.findViewById(R.id.tvPost);
tvLikes = itemView.findViewById(R.id.tvLikes);
ibLike = itemView.findViewById(R.id.ibLike);
}
}
Here need to initialize your adapter class from main activity. and then when data received just call adapter.notifiyDatasetChanged like:
onCreate():
postList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
and from your fetchPostFromDB delete adapter initialization insted of this just put this line testAdapter.notifiyDataSetChanged()
And when click on text button you can update/handle like this:
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
postList.get(holder.getAdapterPosition()).setLikes(incrementLike);
databaseReference.setValue(incrementLike);
notifyDataSetChanged();
}
});

How to add onClickListener on a RecyclerView in Android?

I am developing a car rental app. When user clicks on the the car, he should be directed to a booking page. I tried everything out there but when I click the view / car, I get the following error :
java.lang.NullPointerException: Attempt to invoke interface method 'void com.cuboid.rentacabs.ViewAdapter$onClickListener.onClick(int)' on a null object reference
Everything in the code looks just fine to me,
here's my viewAdapter.java
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder> {
DatabaseReference ref;
FirebaseDatabase fbRref;
Context context;
ArrayList<Model> model;
private onClickListener mListener;
public ViewAdapter(Context c, ArrayList<Model> listItems, onClickListener onClickListener)
{
this.context = c;
this.model = listItems;
this.mListener = onClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.car_details, parent, false);
fbRref = FirebaseDatabase.getInstance();
ref = fbRref.getReference();
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.carName.setText(model.get(position).getmCarName());
holder.seatingCapacity.setText(model.get(position).getmSeatingCapacity());
holder.transmission.setText(model.get(position).getmTransmission());
holder.fuelType.setText(model.get(position).getmFuelType());
//holder.rate.setText(model.get(position).getmRate());
}
#Override
public int getItemCount() {
return model.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView carName,seatingCapacity,transmission,fuelType,rate;
public Button bookBtn;
public onClickListener onClickListener;
public MyViewHolder(#NonNull View itemView)
{
super(itemView);
carName = itemView.findViewById(R.id.car_name);
seatingCapacity = itemView.findViewById(R.id.seating_capacity);
transmission = itemView.findViewById(R.id.transmission_type);
fuelType = itemView.findViewById(R.id.fuel_type);
rate = itemView.findViewById(R.id.rate);
bookBtn =(Button) itemView.findViewById(R.id.book_btn);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onClickListener.onClick(getAdapterPosition());
}
}
public interface onClickListener
{
void onClick(int position);
}
}
this my home fragment:
public class home extends Fragment implements ViewAdapter.onClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public home() {
}
// TODO: Rename and change types and number of parameters
public static home newInstance() {
home fragment = new home();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
//to recycler view.
private RecyclerView recyclerView;
public View view;
private ArrayList<Model> listItem;
ViewAdapter Vadapter;
DatabaseReference dbRef;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_home, container,false);
recyclerView = view.findViewById(R.id.carDetailsContainer);
listItem = new ArrayList<Model>();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
dbRef = FirebaseDatabase.getInstance().getReference().child("Cars");
Vadapter = new ViewAdapter(getContext(),listItem,this);
//recyclerView.OnClickListener();
return view;
}
#Override
public void onStart() {
super.onStart();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Model model = new Model(ds.child("Name").getValue().toString(),ds.child("Seating_Capacity").getValue().toString(),ds.child("Fuel").getValue().toString(),ds.child("Transmission").getValue().toString(),ds.child("Rate").getValue().toString());
listItem.add(model);
}
recyclerView.setAdapter(Vadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
dbRef.addValueEventListener(valueEventListener);
}
#Override
public void onClick(int position) {
listItem.get(position);
Log.d(TAG, "onClick: item"+ position);
startActivity(new Intent(getActivity(), booking.class));
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
thanks in advance.
You did a small mistake.
just replace this
#Override
public void onClick(View v) {
onClickListener.onClick(getAdapterPosition());
}
To this
#Override
public void onClick(View v) {
mListener.onClick(getAdapterPosition());
}
Use it Like this as shown below:
itemView.setOnClickListener(this);
#Override
public void onClick(View v) {
if (v.getId() == id of itemView(R.id.itemview)){
//do not use this
onClickListener.onClick(getAdapterPosition());
//just call the function you need to call on Click of itemview
}
}
Hope this helps

How to filter RecyclerView data in Fragment

I do not know how to filter results from RecyclerView which is being displayed in Fragment.
If possible, I want to merge some of these codes into one java file.
i have searched on Google for some examples, but most of them are implemented in Activity instead.
My fragment code :
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private AdvertiseAdapter advertiseAdapter;
private List<Advertise> advertiseList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search,container,false);
recyclerView = view.findViewById(R.id.searchResult_view);
new DatabaseHelper().readProperty(new DatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Advertise> advertiseList, List<String> keys) {
new RecyclerViewConfig().setConfig(recyclerView,getContext(),advertiseList,keys);
}
});
return view;
}
My DatabaseHelper
public class DatabaseHelper {
private FirebaseDatabase firebaseDatabase;
private DatabaseReference reference;
private List<Advertise> property = new ArrayList<>();
public interface DataStatus{
void DataIsLoaded(List<Advertise> ads,List<String> keys);
}
public DatabaseHelper() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference("Property");
}
public void readProperty(final DataStatus dataStatus){
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
property.clear();
List<String> propertyKeys = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()){
for (DataSnapshot propertySnapshot : userSnapshot.getChildren()){
propertyKeys.add(propertySnapshot.getKey());
Advertise advertise = propertySnapshot.getValue(Advertise.class);
property.add(advertise);
}
}
dataStatus.DataIsLoaded(property,propertyKeys);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
My RecyclerViewConfig code :
public class RecyclerViewConfig {
private Context mContext;
private PropertyAdapter propertyAdapter;
public void setConfig(RecyclerView recyclerView, Context context, List<Advertise> advertiseList, List<String> keys){
mContext = context;
propertyAdapter = new PropertyAdapter(advertiseList,keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(propertyAdapter);
}
class PropertyItemView extends RecyclerView.ViewHolder{
//private ImageView PropertyImage;
private TextView PropertyName;
private TextView PropertyPostal;
private TextView PropertyState;
private TextView PropertyDetail;
private String key;
public PropertyItemView(ViewGroup parent){
super(LayoutInflater.from(mContext)
.inflate(R.layout.search_view,parent,false));
//PropertyImage = itemView.findViewById(R.id.advertiseImage);
PropertyName = itemView.findViewById(R.id.advertiseName);
PropertyState = itemView.findViewById(R.id.advertiseState);
PropertyPostal = itemView.findViewById(R.id.advertisePostal);
PropertyDetail = itemView.findViewById(R.id.advertiseDetail);
}
public void bind(Advertise advertise,String key){
//PropertyImage.setImageDrawable(advertise.getProperty_imageUrl());
PropertyName.setText(advertise.getName());
PropertyState.setText(advertise.getState());
PropertyPostal.setText(advertise.getPostal());
PropertyDetail.setText(advertise.getDetail());
this.key = key;
}
}
class PropertyAdapter extends RecyclerView.Adapter<PropertyItemView>{
private List<Advertise> advertiseList;
private List<String> mkeys;
public PropertyAdapter(List<Advertise> advertiseList, List<String> mkeys) {
this.advertiseList = advertiseList;
this.mkeys = mkeys;
}
#NonNull
#Override
public PropertyItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new PropertyItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull PropertyItemView holder, int position) {
holder.bind(advertiseList.get(position),mkeys.get(position));
final Advertise ads = advertiseList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent redirect = new Intent(mContext,PropertyActivity.class);
redirect.putExtra("propertyID", ads.getPropertyID());
mContext.startActivity(redirect);
}
});
}
#Override
public int getItemCount() {
return advertiseList.size();
}
public void updateList(List<String> newList){
mkeys = new ArrayList<>();
mkeys.addAll(newList);
notifyDataSetChanged();
}
}

Custom methods in adapter are not resolving in android

I have 2 methods inside of adapter class.
addValues(brandMap);
setBrandMap(brandMap);
that I'm trying to call after async call. However, the compiler is complaining that it cannot resolve these methods. What is the issue?
This is complete class.
public class FragmentBrandList extends ListFragment {
private String TAG = getClass().getSimpleName();
private Map<String, Brand> brandMap = new ConcurrentHashMap<>();
private RecyclerView.Adapter adapter;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private RecyclerView recyclerView;
private Query query = database.getReference("brands").orderByChild("name");
public FragmentBrandList() {
}
public static FragmentBrandList newInstance(int num) {
FragmentBrandList f = new FragmentBrandList();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.recycler_list, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
RecyclerView.setLayoutManager(mLayoutManager);
adapter = new FragmentBrandList.MyAdapter(Utility.getBrandMap(), getActivity());
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Brand brand = Utility.getBrands().get(position);
Intent intent = new Intent(getActivity(), ActivityProductList.class);
intent.putExtra("BrandId", brand.getId());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Brand brand = dataSnapshot1.getValue(Brand.class);
brandMap.put(brand.getId(), brand);
}
Utility.setBrandMap(brandMap);
adapter.addValues(brandMap);
adapter.setBrandMap(brandMap);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
Utility.displayToast("Failed to read value." + error.toException());
}
});
return v;
}
Adapter class
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Brand> brandList = new ArrayList<>();
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public MyViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.thumbnail);
}
}
public MyAdapter(Map<String, Brand> brands, Context context) {
//public MyAdapter(List<Brand> brands, Context context) {
this.brandList = new ArrayList<>(brandMap.values());
//this.brandList = brands;
this.context = context;
}
public void setBrandMap(Map<String, Brand> brandMap){
this.brandList = new ArrayList<>(brandMap.values());
notifyDataSetChanged();
}
public void addValues(Map<String, Brand> brands){
brandList.clear();
brandList.addAll(brands.values());
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_brand, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if (brandList != null && brandList.size() > 0) {
Brand brand = brandList.get(position);
Glide.with(context).load(String.valueOf(brand.getImage()))
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(holder.imageView);
}
}
#Override
public int getItemCount() {
return brandList.size();
}
}
You have declared your adapter field as:
private RecyclerView.Adapter adapter;
That means wherever you use it, you'll see it as just a RecyclerView.Adapter, which doesn't have your custom methods on it. It doesn't matter that you've assigned there a subclass of RecyclerView.Adapter that has extra methods. It is because you might've assigned there a different subclass that didn't have those methods.
If you want to use your custom methods then change the declaration to:
private MyAdapter adapter;
Then you can use all methods declared in MyAdapter and inherited from superclasses. The tradeoff is that you cannot assign there any other subclass of RecyclerView.Adapter, but thanks to that compiler can know you can always use your extra methods.
The problem is this line.
private RecyclerView.Adapter adapter;
As you are holding your custom adapter object in the Base reference, hence those methods of your custom adapter is not visible to you. Change the reference to the type of your Custom Adapter and it should work fine.

Categories

Resources