Search code examples
javaandroidandroid-intentandroid-activityandroid-recyclerview

Android: Always receiving null object in extras passed in the intent


I am creating a recycler view in my app and fetching data from firestore for the same. In the process, I am passing some arguments to the intent which is called when an item in the recycler view is clicked.

RecyclerView recyclerView = findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new LearningModuleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
                LearningModule learningModule = documentSnapshot.toObject(LearningModule.class);
                String id=documentSnapshot.getId();
                String path = documentSnapshot.getReference().getPath();
                String title = (String) documentSnapshot.get("title");
                System.out.println("what did i get from document snapshot? id: "+id+" path:"+path+" title:"+title);
                Intent intent = new Intent(learn.this,learn_content.class);
                intent.putExtra("title",title);
                startActivity(intent);
            }
        });

The output from the print statements in above code is as follows :

what did i get from document snapshot? id: EsHW9FGjVe8A3pG4 path:LearningModules/EsHW9FGjVe8A3pG4 title:Front Load vs Top Load

The onClick method of the called activity looks like this :

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_learn_view_pager);
        viewPager = findViewById(R.id.pager);
        progressBar = findViewById(R.id.progressBarViewPager);
        Bundle extras;
        extras = getIntent().getExtras();
        System.out.println("captured form the first " + extras.getString("title"));

However, this piece of code throws an error NullPointerException for the print statement.

Where am I going wrong ?

Additional code:

  • Adapter
public class LearningModuleAdapter extends FirestoreRecyclerAdapter<LearningModule, LearningModuleAdapter.LearningModuleViewHolder> {
    private OnItemClickListener listener;


    public LearningModuleAdapter(@NonNull FirestoreRecyclerOptions<LearningModule> options) {
        super(options);
    }


    @Override
    protected void onBindViewHolder(@NonNull final LearningModuleViewHolder holder, final int position, @NonNull LearningModule model) {
        holder.title.setText(model.getTitle());
//        holder.img.setImageResource(model.getImg());

    }

    @NonNull
    @Override
    public LearningModuleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
        return new LearningModuleViewHolder(v);
    }


    public class LearningModuleViewHolder extends RecyclerView.ViewHolder {
        public View view;
        public TextView title;
        public ImageView img;

        public LearningModuleViewHolder(View v) {
            super(v);
            view = v;
            img = itemView.findViewById(R.id.list_image);
            title = itemView.findViewById(R.id.list_text_title);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.out.println("The click was captured");
                    int position = getAdapterPosition();
                    if(position!=RecyclerView.NO_POSITION && null!=listener){
                        listener.onItemClick(getSnapshots().getSnapshot(position),position);
                    }
                    Intent intent = new Intent(view.getContext(), learn_content.class);
                    view.getContext().startActivity(intent);
                }
            });
        }

    }

    public interface OnItemClickListener{
        void onItemClick(DocumentSnapshot documentSnapshot,int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }


}
  • Error Stacktrace
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gigforce.app/com.gigforce.app.learn_content}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
        at com.gigforce.app.learn_content.onCreate(learn_content.java:45)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356)

Solution

  • You are calling startActivity twice that cause the problem.

    Option - 1: Try removing inside itemView.setOnClickListener like below :

    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("The click was captured");
            int position = getAdapterPosition();
            if(position!=RecyclerView.NO_POSITION && null!=listener){
                listener.onItemClick(getSnapshots().getSnapshot(position),position);
            }
    
            //Intent intent = new Intent(view.getContext(), learn_content.class);
            //view.getContext().startActivity(intent);
        }
    });
    

    Option - 2: Try to start activity inside itemView.setOnClickListener and remove OnItemClickListener related code like below :

    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("The click was captured");
            int position = getAdapterPosition();
    
            /*if(position!=RecyclerView.NO_POSITION && null!=listener){
                listener.onItemClick(getSnapshots().getSnapshot(position),position);
            }*/
    
            Intent intent = new Intent(view.getContext(), learn_content.class);
    
            DocumentSnapshot documentSnapshot = getSnapshots().getSnapshot(position);
            String title = (String) documentSnapshot.get("title");
    
            intent.putExtra("title",title);
            view.getContext().startActivity(intent);
        }
    });