Another Null object reference [duplicate] - java

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>();

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()));
}
});
}

RecyclerViewClickListener returns null

I have two activities and two layouts. When I display the list in the first activity, everything works and gives me the number of the item in the list when clicked, but when I try to repeat the same thing in the second activity, it gives me that the RecyclerViewClickListener listener is null.
Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<String> array;
private RecyclerViewClickListener listener;
public MyAdapter( ArrayList<String> arrays, RecyclerViewClickListener listener)
{
this.listener = listener;
this.array = arrays;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(array.get(position));
}
#Override
public int getItemCount() {
return array.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView textView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_card);
itemView.setOnClickListener(this);
System.out.println(itemView);
}
#Override
public void onClick(View v) {
System.out.println(listener);
System.out.println(v);
System.out.println(getAdapterPosition());
listener.onClick(v, getAdapterPosition());
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
first activity:
ArrayList<String> list_of_name= new ArrayList<>();
private RecyclerView recyclerView;
private MyAdapter.RecyclerViewClickListener listener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acticity1);
recyclerView = findViewById(R.id.recyclerView);
list();
}
public void list() {
MyAdapter myAdapter = new MyAdapter(list_of_name, listener);
recyclerView.setAdapter(myAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listener = (v, position) -> {
itemPosition = list_of_name.get(position);
Syste.out.println(itemPosition );
};
}
Second activity:
private RecyclerView recyclerView;
private MyAdapter.RecyclerViewClickListener listener;
ArrayList<String> list2= new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acticity2);
recyclerView = findViewById(R.id.recyclerView1);
File internalStorageDir = getFilesDir();
File alice = new File(internalStorageDir, "file/");
for (File file : alice.listFiles()) {
list2.add(0, file.getName());
}
view();
}
public void view()
{
MyAdapter adapter = new MyAdapter(list2, listener);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listener = (v, position) -> {
itemPosition = list2.get(position);
Syste.out.println(itemPosition );
};
}
Error:
I/System.out: null
android.widget.LinearLayout{ecdf5a1 VFE...C.. ...P.... 0,0-1080,167}
0
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 28268
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.myapplication.recycler.MyAdapter$RecyclerViewClickListener.onClick(android.view.View, int)' on a null object reference
at com.example.myapplication.recycler.MyAdapter$MyViewHolder.onClick(MyAdapter.java:59)
at android.view.View.performClick(View.java:7185)
at android.view.View.performClickInternal(View.java:7162)
at android.view.View.access$3500(View.java:819)
at android.view.View$PerformClick.run(View.java:27684)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
E/MQSEventManagerDelegate: failed to get MQSService.
I can’t understand why in the first case it processes the click normally, and in the second it says that the RecyclerViewClickListener is null
public void list() {
MyAdapter myAdapter = new MyAdapter(list_of_name, listener);
recyclerView.setAdapter(myAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listener = (v, position) -> {
itemPosition = list_of_name.get(position);
System.out.println(itemPosition );
};
}
This is where the issue is coming. You are passing the listener first and then initialising it later. This is causing it to be null. Why don't you try this?:
public void list() {
listener = (v, position) -> {
itemPosition = list_of_name.get(position);
System.out.println(itemPosition );
};
MyAdapter myAdapter = new MyAdapter(list_of_name, listener);
recyclerView.setAdapter(myAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this);
}

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);
}
});

Problem in making the items in RecyclerView clickable

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.

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