java – Intent not working in recyclerview onclick-ThrowExceptions

Exception or error:

I created a recyclerview that displays a list of users from firebase, i want to send user to another activity whenever they clicks on an item in the list but it kept saying “CurrentActivity is not an enclosing tag” whenever i call on intent.
Heres the code

  public class UserActivity extends AppCompatActivity {
        private Toolbar mToobar;

        private RecyclerView recyclerView;
        private UserAdapter adapter;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_user);

            mToobar = findViewById(R.id.toolbar);
            setSupportActionBar(mToobar);
            Objects.requireNonNull(getSupportActionBar()).setTitle("Find New Friends");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToobar.setTitleTextColor(Color.parseColor("WHITE"));

            recyclerView = findViewById(R.id.recycler);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            //recyclerView.setHasFixedSize(true);



            FirebaseRecyclerOptions<UserModel> options = new FirebaseRecyclerOptions.Builder<UserModel>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("Users"), UserModel.class)
                    .build();

            adapter = new UserAdapter(options);
            recyclerView.setAdapter(adapter);
            recyclerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(UserActivity.this, ProfileActivity.class);
                    startActivity(i);
                }
            });
        }



        @Override
        protected void onStart() {
            super.onStart();
            adapter.startListening();
        }

        @Override
        protected void onStop() {
            super.onStop();
            adapter.stopListening();
        }


    }

Here’s the adapter class

public class UserAdapter extends FirebaseRecyclerAdapter<UserModel, UserAdapter.UserViewHolder> {



    /**
     * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
     * {@link FirebaseRecyclerOptions} for configuration options.
     *
     * @param options
     */
    public UserAdapter(@NonNull FirebaseRecyclerOptions<UserModel> options) {
        super(options);
    }


    @Override
    protected void onBindViewHolder(@NonNull UserViewHolder holder, int position, @NonNull UserModel model) {

        holder.mName.setText(model.getName());
        holder.mStatus.setText(model.getStatus());
        Picasso.get().load(model.getImage()).placeholder(R.drawable.avatar).into(holder.mImage);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserActivity.this, ProfileActivity.class);
                startActivity(intent);
                //heres the error, UserActivity is not an enclosing tag
            }
        });


    }

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

    class UserViewHolder extends RecyclerView.ViewHolder{

        TextView mName, mStatus;
        CircleImageView mImage;

        public UserViewHolder(@NonNull View itemView) {
            super(itemView);

            mName = itemView.findViewById(R.id.user_displayname);
            mStatus = itemView.findViewById(R.id.user_status);
            mImage = itemView.findViewById(R.id.user_photo);
        }
    }
}

This is the model class

public class UserModel {
    public String name;
           String image;
           String status;

    public UserModel() {
    }

    @Override
    public String toString() {
        return "UserModel{" +
                "name='" + name + '\'' +
                ", image='" + image + '\'' +
                ", status='" + status + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

Can someone help me on better way on how to implement onClickListener, please?

How to solve:

use holder.itemView.getContext() instead of UserActivity.this in your adapter classs.

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = holder.itemView.getContext();
            Intent intent = new Intent(context, ProfileActivity.class);
            context.startActivity(intent);
        }
    })

And removed this block of code because you need to set click listeners on individual views within the RecyclerView, rather than the RecyclerView as a whole.

recyclerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(UserActivity.this, ProfileActivity.class);
                startActivity(i);
            }
        });

###

You can also send the View.onClickListener to the constructor of the list something like:

View.onClickListener listener;

public UserAdapter(@NonNull FirebaseRecyclerOptions<UserModel> options, View.onClickListener listener) {
        super(options);
        this.listener = listener;
    }

holder.itemView.setOnClickListener(listener); //this part will be in your onBindViewHolder

in your activity you need to implement the interface View.onClickListener and in

@Override
public void onClick(View v){
     Intent i = new Intent(UserActivity.this, ProfileActivity.class);
                startActivity(i);
}

and when you create your adapter use the following code:

FirebaseRecyclerOptions<UserModel> options = new FirebaseRecyclerOptions.Builder<UserModel>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("Users"), UserModel.class)
                    .build();

            adapter = new UserAdapter(options,this);

###

You are passing UserActivity as a current activity. Pls pass context to your adapter constructor.

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder>() {
    private ArrayList<UserResult> userList;
    private Activity mActivity;

    public AdapterChatList(Activity mActivity, ArrayList<UserResult> mUserList) {
        this.mActivity = mActivity;
        this.userList = mUserList;
    }
}

Set context to your startactivity.

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mActivity,ProfileActivity.class);
            startActivity(intent);
            //Pass context object as your current activity
        }
    });

Pass context in your activity where you define the adapter.

 mUserAdapter = new UserAdapter (getActivity(), userArrayList);
 recyclerView.setAdapter(mUserAdapter );

Leave a Reply

Your email address will not be published. Required fields are marked *