Problem in making the items in RecyclerView clickable - java

I know there are questions like this, but non solving mine..
I'm trying to make 'OnItemClickListener' of 'RecyclerView' , but when I run the app it stops..
can you tell me where is the error??
Here is the code: (Note the error is in making the item clickable)
public class TeacherActivity extends AppCompatActivity {
private FirebaseAuth mAuth=FirebaseAuth.getInstance();
private FirebaseUser currentUser= mAuth.getCurrentUser();;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private String UserId =currentUser.getUid();
private static String city;
private TeacherAdapter teacherAdapter;
public static final String EXTRA_PATH = "com.example.exercise.EXTRA_PATH";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher);
setUpRecyclerView();
teacherAdapter.setOnItemClickListener(new TeacherAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
String path = documentSnapshot.getReference().getPath();
Intent intent = new Intent(TeacherActivity.this, SecondActivity.class);
intent.putExtra(EXTRA_PATH, path);
startActivity(intent);
}
});
}// end of onCreate
private void setUpRecyclerView(){
Query query = db.collection("Teachers");
FirestoreRecyclerOptions < Teacher > options = new
FirestoreRecyclerOptions.Builder<Teacher>()
.setQuery(query, Teacher.class)
.build();
teacherAdapter = new TeacherAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true); //for performane reasons
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(teacherAdapter);
teacherAdapter.startListening();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
teacherAdapter.stopListening();
}
}// end of class
And this is the 'adapter' of 'RecyclerView':
public class TeacherAdapter extends FirestoreRecyclerAdapter<Teacher,
TeacherAdapter.TeacherHolder> {
private OnItemClickListener listener;
public TeacherAdapter(#NonNull FirestoreRecyclerOptions<Teacher> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull TeacherHolder holder, int i, #NonNull Teacher
teacher) {
holder.tv_teacher_name.setText(teacher.getName());
holder.tv_cv.setText(teacher.getCv());
}
#NonNull
#Override
public TeacherHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.teacher_item, parent, false);
return new TeacherHolder(v);
}
class TeacherHolder extends RecyclerView.ViewHolder {
TextView tv_teacher_name;
TextView tv_cv;
public TeacherHolder(#NonNull View itemView) {
super(itemView);
tv_teacher_name = itemView.findViewById(R.id.teacher_name);
tv_cv = itemView.findViewById(R.id.tv_cv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null){
listener.onItemClick(getSnapshots().getSnapshot(position), position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
}
Part of logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.exercise, PID: 29966
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.exercise/com.example.exercise.TeacherActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.exercise.TeacherAdapter.setOnItemClickListener(com.example.exercise.TeacherAdapter$OnItemClickListener)' on a null object reference

You are getting the following error:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.exercise, PID: 29966 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.exercise/com.example.exercise.TeacherActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.exercise.TeacherAdapter.setOnItemClickListener(com.example.exercise.TeacherAdapter$OnItemClickListener)' on a null object reference
Because you are calling .setOnItemClickListener() on your teacherAdapter object which is null at that point in time. To solve this, you should simply move the following block of code:
teacherAdapter.setOnItemClickListener(new TeacherAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
String path = documentSnapshot.getReference().getPath();
Intent intent = new Intent(TeacherActivity.this, SecondActivity.class);
intent.putExtra(EXTRA_PATH, path);
startActivity(intent);
}
});
Right after the declaration of your adapter:
teacherAdapter = new TeacherAdapter(options);
In your setUpRecyclerView() method and your problem will be solved.

Related

Crasing app with 'java.lang.String android.content.Context.getPackageName()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last month.
I've created a recycler view to display data. I want to display a toast message when clicking interview. so, I set this,
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "item clicked!!", Toast.LENGTH_SHORT).show();
}
});
in onbindViewHolder method in the adapter class. After run the app app crashed and displayed this error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ss.newapp, PID: 27382
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.widget.Toast.<init>(Toast.java:178)
at android.widget.Toast.makeText(Toast.java:595)
at android.widget.Toast.makeText(Toast.java:583)
at com.ss.newapp.DetailsAdapter$1.onClick(DetailsAdapter.java:50)
at android.view.View.performClick(View.java:7509)
at android.view.View.performClickInternal(View.java:7486)
at android.view.View.access$3600(View.java:841)
at android.view.View$PerformClick.run(View.java:28709)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8061)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
D/OOMEventManagerFK: checkEventAndDumpForJE: 0
I/Process: Sending signal. PID: 27382 SIG: 9
Disconnected from the target VM, address: 'localhost:53359', transport: 'socket'
I checked other solutions reguarding to this error in SO, but it didn't work for my code.
Here is my Adapter.java class
public class DetailsAdapter extends
RecyclerView.Adapter<DetailsAdapter.ViewHolder> {
private List<Details> detailsList;
Context context;
public DetailsAdapter(List<Details> detailsList, Context context){
this.detailsList = detailsList;
this.context = context;
}
#NonNull
#Override
public DetailsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DetailsAdapter.ViewHolder holder,
int position) {
holder.txtCusCode.setText(detailsList.get(position).getCode());
holder.txtCusName.setText(detailsList.get(position).getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "item clicked!!", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return detailsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView txtCusName, txtCusCode;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtCusCode = itemView.findViewById(R.id.cusCodeTxt);
txtCusName = itemView.findViewById(R.id.cusNameTxt);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Context context;
TextView textView;
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
DetailsAdapter detailsAdapter;
List<Details> detailsList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
recyclerView = findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
detailsAdapter = new DetailsAdapter(detailsList, context);
recyclerView.setAdapter(detailsAdapter);
context = getApplicationContext();
getDetails();
}
private void getDetails() {
}
You have get data first and then set adapter(copy this and try)
public class MainActivity extends AppCompatActivity {
Context context;
TextView textView;
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
DetailsAdapter detailsAdapter;
List<Details> detailsList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
getDetails();
textView = findViewById(R.id.textView);
recyclerView = findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
detailsAdapter = new DetailsAdapter(detailsList, context);
recyclerView.setAdapter(detailsAdapter);
}
private void getDetails() {
RetrofitClient.getRetrofitClient().getDetails().enqueue(new Callback<List<Details>>() {
#Override
public void onResponse(Call<List<Details>> call, Response<List<Details>> response) {
if(response.isSuccessful() && response.body() != null){
detailsList.addAll(response.body());
detailsAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<List<Details>> call, Throwable t) {
textView.setText((t.getMessage()));
}
});
}

Why i can't click my item on recyclerview

I can't click the item on recyclerview, I don't know why, so can somebody help me to clear this problem?
so this in my code in MainActivity, and I call this function in onCreate :
private void showRecyclerList(){
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
UserAdapter userAdapter = new UserAdapter(this, userModel);
recyclerView.setAdapter(userAdapter);
userAdapter.setOnItemClickCallback(new UserAdapter.OnItemClickCallback() {
#Override
public void onItemClicked(UserModel data) {
Intent intent = new Intent(MainActivity.this, UserDetailActivity.class);
intent.putExtra(UserDetailActivity.EXTRA_DATA, (Parcelable) userModel);
startActivity(intent);
}
});
}
I used the Interface from OnItemClickCallback and I up it on User Adapter, and this is my UserAdapter:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ListViewHolder> {
private Context context;
private List<UserModel> userData = new ArrayList<>();
private OnItemClickCallback onItemClickCallback;
public void setOnItemClickCallback(final OnItemClickCallback onItemClickCallback) {
this.onItemClickCallback = onItemClickCallback;
}
public static final String DATA_EXTRA = "data_extra";
public UserAdapter(Context context, List<UserModel> userData) {
this.context = context;
this.userData = userData;
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_user, parent,false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ListViewHolder holder, int position) {
//UserModel user = userData.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickCallback.onItemClicked(userData.get(holder.getAdapterPosition()));
}
});
Glide.with(context)
.load(userData.get(position).getAvatarUrl())
.into(holder.imgPhoto);
holder.tvName.setText(userData.get(position).getLogin());
}
#Override
public int getItemCount() {
return userData.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder
{
ImageView imgPhoto;
TextView tvName;
public ListViewHolder(View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.iv_avatar);
tvName = itemView.findViewById(R.id.tv_name);
}
}
public interface OnItemClickCallback {
void onItemClicked(UserModel data);
}
and this is my error message :
java.lang.NullPointerException: Attempt to invoke interface method 'void com.dicoding.githubuserwithapi.UserAdapter$OnItemClickCallback.onItemClicked(com.dicoding.githubuserwithapi.model.UserModel)' on a null object reference
at com.dicoding.githubuserwithapi.UserAdapter$1.onClick(UserAdapter.java:60)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
I/Process: Sending signal. PID: 9602 SIG: 9
I have an error in UserAdapter line 60
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**onItemClickCallback.onItemClicked(userData.get(holder.getAdapterPosition()));**
}
});
on my UserModel class, there is only the data from the user and I used Parcelable on it.
I think I can't get the position, but I don't know where can I fix it, so can u guys help me with this problem..
When creating LayoutInflater you should use parent.context.
View view = LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent,false);
Why are you calling adapter's getAdapterPosition() if position is already available to you as a parameter of onBindViewHolder()?
onItemClickCallback.onItemClicked(userData.get(position));
When you're defining that click listener you're not using the data you passed to it.
userAdapter.setOnItemClickCallback(new UserAdapter.OnItemClickCallback() {
#Override
public void onItemClicked(UserModel data) {
Intent intent = new Intent(MainActivity.this, UserDetailActivity.class);
intent.putExtra(UserDetailActivity.EXTRA_DATA, (Parcelable) **userModel**);
startActivity(intent);
}
});

Another Null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I'm new and can't seem to find the error even though I've read through similar topics on the site. I understand the gist of my error but cant seem to fix it. I'm making a basic "shopping cart" for a project, and would like to pass items from a custom ArrayList to another custom ArrayList via onClickListener in RecycleView. . I have a feeling that it is with the "position", as it is the only common element between the lines of code in question. I have marked the three lines that came up in the error messages.
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MainAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<Inventory> mInventoryList;
private int position;
private Button button;
private ArrayList<Inventory> cartList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Estimate("XXX000","John Smith", "john#gmail.com", cartList);
InputStream inputStream = getResources().openRawResource(R.raw.data);
CSVreader csvFile = new CSVreader(inputStream);
ArrayList<Inventory> inventoryList = (ArrayList<Inventory>) csvFile.read();
mRecyclerView = findViewById(R.id.recyclerviewMain);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MainAdapter(inventoryList);
mInventoryList = inventoryList;
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), EstimateActivity.class);
intent.putExtra("cartList", cartList);
v.getContext().startActivity(intent);
}
});
mAdapter.setOnItemClickListener(new MainAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
addToCart(position); //ERROR HERE
}
});
}
public void addToCart(int position){
cartList.add(position, new Inventory()); //ERROR HERE
}
}
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
private ArrayList<Inventory> mInventoryList;
private ArrayList<Inventory> mCartList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class MainViewHolder extends RecyclerView.ViewHolder {
private TextView cardCode;
private TextView cardName;
private CardView containerView;
private ArrayList<Inventory> cartList;
public MainViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
cardCode = itemView.findViewById(R.id.text_row_code_viewMain);
cardName = itemView.findViewById(R.id.text_row_name_viewMain);
itemView = itemView.findViewById(R.id.container_viewMain);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null ){
int position = getAdapterPosition(); //ERROR HERE
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public MainAdapter(ArrayList<Inventory> inventoryList){
mInventoryList = inventoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_row_main, parent, false);
MainViewHolder mvh = new MainViewHolder(view, mListener);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
Inventory currentItem = mInventoryList.get(position);
holder.cardName.setText(currentItem.getName());
holder.cardCode.setText(currentItem.getCode());
holder.itemView.setTag(currentItem);
}
#Override
public int getItemCount() {
return mInventoryList.size();
}
}
11357/com.jourdon.cartsavetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jourdon.cartsavetest, PID: 11357
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.ArrayList.add(int, java.lang.Object)' on a null object reference
at com.jourdon.cartsavetest.MainActivity.addToCart(MainActivity.java:76)
at com.jourdon.cartsavetest.MainActivity$2.onItemClick(MainActivity.java:69)
at com.jourdon.cartsavetest.MainAdapter$MainViewHolder$1.onClick(MainAdapter.java:49)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2020-11-04 17:51:47.720 11357-11357/? I/Process: Sending signal. PID: 11357 SIG: 9
Just declaring your variable cartList, which you did on this line:
private ArrayList<Inventory> cartList;
is not enough. You also need to initialize this variable with an actual list that you can add items to.
When you declare a variable, you're telling Java that you plan to use an object of a certain type in your program, and you are telling Java what the name of the variable is along with the type.
But, declaring a variable doesn't give you an actual list. What you need to do is create a list and store it in your variable. You probably want to do this in the MainViewHolder constructor method. The initialization line might look like this:
cartList = new ArrayList<Inventory>();

RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView Adapter ADAPTER

Tried using recycler view inside recycler view the first adapter works fine but the second adapter never runs
tired fixing it over and over nothing works....help
The second recycler view is retrieving data from Firebase
The Data from firebase is received but never set to the required text views.
Activity
public class ScheduleOrder extends AppCompatActivity implements IFirebaseLoadListener {
DeviceSession deviceSession;
UserSession userSession;
String Device_Id="",User_Id="";
MyItemAdapter myItemAdapter;
IFirebaseLoadListener iFirebaseLoadListener;
List<String> Name;
List<ItemData>itemData;
ItemData itemData1;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_order);
itemData1=new ItemData();
deviceSession = new DeviceSession(getApplicationContext());
Device_Id = deviceSession.getDeviceDetails();
userSession = new UserSession(getApplicationContext());
final HashMap<String, String> user = userSession.getUserDetails();
User_Id = user.get(UserSession.User_Id);
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.schedule_add);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),Schedule_Order.class);
startActivity(i);
finish();
}
});
myData=FirebaseDatabase.getInstance().getReference("Cart_Schedule"+"/"+Device_Id);
iFirebaseLoadListener=this;
my_recycler_view=findViewById(R.id.my_recyclr_view);
my_recycler_view.setHasFixedSize(true);
// my_recycler_view1.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
// my_recycler_view1.setLayoutManager(new LinearLayoutManager(this));
getFirebaseData();
}
private void getFirebaseData() {
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<ItemGroup>itemGroups=new ArrayList<>();
Name=new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
ItemGroup itemGroup=new ItemGroup();
itemGroup.setD_Time(groupSnapShot.child("d_Time").getValue(true).toString());
itemGroup.setF_Amount(groupSnapShot.child("f_Amount").getValue(true).toString());
for(DataSnapshot newdatasnap:groupSnapShot.child("listItem").getChildren()){
itemData1.setA_Item_name(newdatasnap.child("a_Item_name").getValue().toString());
itemData1.setB_Quantity(newdatasnap.child("b_Quantity").getValue().toString());
itemData1.setC_Price(newdatasnap.child("b_Quantity").getValue().toString());
Name.add(newdatasnap.child("a_Item_name").getValue().toString());
Name.add(newdatasnap.child("c_Price").getValue().toString());
Name.add(newdatasnap.child("b_Quantity").getValue().toString());
Log.d("JADOO", "onDataChange: ??? "+itemData1.getA_Item_name());
Log.d("JADOO", "onDataChange: ??? "+itemData1.getB_Quantity());
Log.d("JADOO", "onDataChange: ??? "+itemData1.getC_Price());
Log.d("JADOO", "onDataChange: ??? "+Name);}
Log.d("JADOO", "onDataChange: ====================================================");
itemGroups.add(itemGroup);
Name.clear();
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<ItemGroup> itemGroupList) {
Log.d("JADOO", "onDataChange: Setting Adapter");
MyItemGroupAdapter adapter = new MyItemGroupAdapter(ScheduleOrder.this,itemGroupList,itemData1);
my_recycler_view.setAdapter(adapter);
}
#Override
public void onFirebaseLoadFailed(String message) {
}
}
First Adapter Java file
public class MyItemGroupAdapter extends RecyclerView.Adapter<MyItemGroupAdapter.MyViewHolder> {
private Context context;
private List<ItemGroup>dataList;
private ItemData name;
public MyItemGroupAdapter(Context context, List<ItemGroup> dataList,ItemData data) {
this.context = context;
this.dataList = dataList;
this.name=data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView=LayoutInflater.from(context).inflate(R.layout.tempcartlayout,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
MyItemAdapter itemListAdapter = new MyItemAdapter(context,name);
myViewHolder.timee.setText(dataList.get(i).getD_Time());
myViewHolder.cost.setText(dataList.get(i).getF_Amount());
Log.d("JADOO", "onDataChange: IN MY ITEM GRP ADAPTER "+name.getA_Item_name());
myViewHolder.recycler_view_item_list.setHasFixedSize(true);
myViewHolder.recycler_view_item_list.setLayoutManager(new CustomLinearLayoutManager(context,LinearLayoutManager.VERTICAL,false));
myViewHolder.recycler_view_item_list.setAdapter(itemListAdapter);
myViewHolder.recycler_view_item_list.setNestedScrollingEnabled(false);
myViewHolder.can.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Button More : "+myViewHolder.timee.getText()+" -- "+myViewHolder.cost.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (dataList != null ? dataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView timee,cost;
Button can;
RecyclerView recycler_view_item_list;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
timee=itemView.findViewById(R.id.reorder_time);
cost=itemView.findViewById(R.id.reorder_cost);
can=itemView.findViewById(R.id.button);
Log.d("JADOO", "onDataChange: VIEW HOLDER ");
recycler_view_item_list=itemView.findViewById(R.id.schedulecart);
}}}
Second Adapter File
private Context context;
private ItemData name123;
public MyItemAdapter(Context context, ItemData Item_Name) {
this.context = context;
this.name123=Item_Name;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView= LayoutInflater.from(context).inflate(R.layout.cart_list_layout,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
Log.d("JADOO", "onBindViewHolder: IN MY ITEM ADAPTER");
ItemData itemData=new ItemData();
myViewHolder.m_name.setText(itemData.getA_Item_name());
myViewHolder.m_cost.setText(itemData.getC_Price());
myViewHolder.m_quant.setText(itemData.getB_Quantity());
}
#Override
public int getItemCount() {
return 0;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView m_name,m_quant,m_cost;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener){
this.iItemClickListener=iItemClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
m_name=itemView.findViewById(R.id.tv_menu_name1);
m_quant=itemView.findViewById(R.id.quantity);
m_cost=itemView.findViewById(R.id.amount);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view,getAdapterPosition());
}}}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.food.pilo, PID: 28457
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.food.pilo.ScheduleOrder.onFirebaseLoadSuccess(ScheduleOrder.java:161)
at com.food.pilo.ScheduleOrder$2.onDataChange(ScheduleOrder.java:143)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##16.0.4:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)```
Your return value is 0 in Second adapter. Please add arraylist to second adapter.
#Override
public int getItemCount() {
return 0;
}
I think my_recycler_view=findViewById(R.id.my_recyclr_view); or
findViewById(R.id.schedulecart); returning null please check on these lines.

Error: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm creating an app that display videos in a recycler view , I already can storage the videos in Database Firestore , but I'm getting this error when I run my app:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.example.carlos.trendy.FeedRecyclerAdapter.getItemCount(FeedRecyclerAdapter.java:35)
My code:
public class FeedRecyclerAdapter extends RecyclerView.Adapter<FeedRecyclerAdapter.ViewHolder> {
public List<Feed>feedList;
public FeedRecyclerAdapter(List<Feed> feedList){
this.feedList = feedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String desc_data = feedList.get(position).getDesc();
holder.setDesc(desc_data);
}
#Override
public int getItemCount() {
return feedList.size();///ERROR
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView desc;
private View mView;
public ViewHolder(View itemView) {
super(itemView);
mView=itemView;
}
public void setDesc(String descText){
desc = mView.findViewById(R.id.post_desc);
desc.setText(descText);
}
}
}
FeedActivity:
public class FeedActivity extends AppCompatActivity {
private Context mContext = FeedActivity.this;
private static final int ACTIVITY_NUM = 0;
private FirebaseFirestore firebaseFirestore;
private RecyclerView mFeedList;
private List<Feed> feedList;
private FeedRecyclerAdapter feedRecyclerAdapter;
public void videoPicker(View view){
Intent intent = new Intent(FeedActivity.this, postActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
mFeedList = this.findViewById(R.id.feed_list);
feedRecyclerAdapter = new FeedRecyclerAdapter(feedList);
mFeedList.setLayoutManager(new LinearLayoutManager(this));
mFeedList.setAdapter(feedRecyclerAdapter);
feedList = new ArrayList<>();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Posts").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentChange documentChange: documentSnapshots.getDocumentChanges()){
if (documentChange.getType() == DocumentChange.Type.ADDED){
Feed feed = documentChange.getDocument().toObject(Feed.class);
feedList.add(feed);
feedRecyclerAdapter.notifyDataSetChanged();
}
}
}
});
setupBottomNavigationView();
}
private void setupBottomNavigationView() {
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
#Override
protected void onStart() {
super.onStart();
}
public static class FeedViewHolder extends RecyclerView.ViewHolder {
View mView;
public FeedViewHolder(View itemView) {
super(itemView);
itemView = mView;
}
public void setDesc(String desc){
TextView post_desc = mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
}
}
Can anyone help me?
You initialize the adapter here:
feedRecyclerAdapter = new FeedRecyclerAdapter(feedList);
but feedList is null.
You must initialize it
Move all these lines:
feedRecyclerAdapter = new FeedRecyclerAdapter(feedList);
mFeedList.setLayoutManager(new LinearLayoutManager(this));
mFeedList.setAdapter(feedRecyclerAdapter);
after this line:
feedList = new ArrayList<>();

Categories

Resources