1

I'm having an issue trying to create an OnClickListener in my CategoriesAdapter.Java

A short summary of what i'm trying to do: I am trying to build a section of an app that shows the 'Categories' of certain business types i.e. Tech, Finance etc etc

I want to make sure the user is able to click on a category and take them to that desired category of choice basically; "User clicks on 'Finance' User goes to 'Finance' Category.

I'll paste my code here if you can help me that would be great.

CategoriesAdapter.Java

package com.example.tencil.HelperClasses.HomeAdapter;


import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.tencil.R;
import com.example.tencil.User.CategoriesHelperClass;



import java.util.ArrayList;

import static android.content.ContentValues.TAG;

public class CategoriesAdapter extends RecyclerView.Adapter<CategoriesAdapter.ViewHolder> {

ArrayList<CategoriesHelperClass> categories;
private ArrayList<CategoriesHelperClass> mTitle = new ArrayList<>();
private ArrayList<CategoriesHelperClass> mImages = new ArrayList<>();
private android.content.Context mcontext;



public CategoriesAdapter(ArrayList<CategoriesHelperClass> categories) {
    this.categories = categories;
    this.mTitle = mTitle;
    this.mImages = mImages;
    this.mcontext = mcontext;
}



//Returns Categories View Dynamically
public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
    View view = LayoutInflater.from ( parent.getContext () ).inflate ( R.layout.categories_card_design, parent, false );
    ViewHolder holder = new ViewHolder ( view );
    return new ViewHolder ( view );
}

public void onBindViewHolder( ViewHolder holder, int position) {

    Log.d (TAG, "OnBindViewHolder: Called.");
    holder.image.setImageResource ( com.example.tencil.HelperClasses.HomeAdapter.CategoriesHelperClass.getImage () );
    holder.title.setText ( com.example.tencil.HelperClasses.HomeAdapter.CategoriesHelperClass.getTitle () );
    holder.parentLayout.setOnClickListener ( new View.OnClickListener () {

        public void onClick(View v) {
            Log.d (TAG, "OnClick: Clicked on" + mImages.get ( position ));
            Toast.makeText ( mcontext, (CharSequence) mTitle.get ( position ), Toast.LENGTH_SHORT ).show ();
        }
    } );


}

public int getItemCount() {

    return categories.size ();
}

//HOLDS VIEWS
public static class ViewHolder extends RecyclerView.ViewHolder {
    ImageView image;
    TextView title;
    RelativeLayout parentLayout;

    public ViewHolder(View itemView) {
        super ( itemView );


        //HOOKS
        image = itemView.findViewById ( R.id.categories_image );
        title = itemView.findViewById ( R.id.categories_title );
        parentLayout = itemView.findViewById ( R.id.parentLayout );



    }

    }
}

UserDashboard.XML

<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".User.UserDashboard">


    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#fff"
        android:theme="@style/navigationTheme"
        app:headerLayout="@layout/menu_header"
        app:menu="@menu/main_menu" />

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/lightWhite"
        android:orientation="vertical">

        <RelativeLayout

            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:background="@color/colorPrimary"
            android:padding="20dp">


            <ImageView
                android:id="@+id/menu_icon"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/menu_icon" />


        </RelativeLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#fff"
                android:orientation="vertical">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:id="@+id/app_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:fontFamily="@font/raleway_bold"
                        android:paddingTop="8dp"
                        android:text="@string/tencil"
                        android:textColor="@color/colorAccent"
                        android:textSize="28sp" />


                </RelativeLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:orientation="horizontal"
                    android:paddingTop="20dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <RelativeLayout
                            android:id="@+id/card_1"
                            android:layout_width="60dp"
                            android:layout_height="60dp"
                            android:layout_margin="10dp"
                            android:background="@drawable/card_3"
                            android:elevation="8dp"
                            android:onClick="cardClicked1">

                            <ImageView
                                android:layout_width="30dp"
                                android:layout_height="30dp"
                                android:layout_centerInParent="true"
                                android:src="@drawable/tencilw" />

                        </RelativeLayout>

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:text="@string/socialmedis"
                            android:textAlignment="center" />


                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <RelativeLayout
                            android:id="@+id/card_2"
                            android:layout_width="60dp"
                            android:layout_height="60dp"
                            android:layout_margin="10dp"
                            android:background="@drawable/card_1"
                            android:elevation="8dp"
                            android:onClick="cardClicked2">>

                            <ImageView
                                android:layout_width="30dp"
                                android:layout_height="30dp"
                                android:layout_centerInParent="true"
                                android:src="@drawable/piggy" />

                        </RelativeLayout>

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:text="@string/finance"
                            android:textAlignment="center" />


                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <RelativeLayout
                            android:id="@+id/card_3"
                            android:layout_width="60dp"
                            android:layout_height="60dp"
                            android:layout_margin="10dp"
                            android:background="@drawable/card_2"
                            android:elevation="8dp"
                            android:onClick="cardClicked3">

                            <ImageView
                                android:layout_width="50dp"
                                android:layout_height="50dp"
                                android:layout_centerInParent="true"
                                android:src="@drawable/pws" />

                        </RelativeLayout>

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:text="@string/tech"
                            android:textAlignment="center" />


                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <RelativeLayout
                            android:id="@+id/card_4"
                            android:layout_width="60dp"
                            android:layout_height="60dp"
                            android:layout_margin="10dp"
                            android:background="@drawable/card_4"
                            android:elevation="8dp"
                            android:onClick="cardClicked4">

                            <ImageView
                                android:layout_width="30dp"
                                android:layout_height="30dp"
                                android:layout_centerInParent="true"
                                android:src="@drawable/analysisw" />

                        </RelativeLayout>

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:text="@string/fintech"
                            android:textAlignment="center" />


                    </LinearLayout>


                </LinearLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="20dp"
                    android:background="@drawable/banner_background">

                    <LinearLayout
                        android:id="@+id/featured_background"
                        android:layout_width="170dp"
                        android:layout_height="280dp"
                        android:layout_margin="10dp"
                        android:background="@drawable/banner_background"
                        android:orientation="vertical">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:layout_marginTop="50dp"
                            android:text="@string/featured_companies"
                            android:textAllCaps="true"
                            android:textColor="#000"
                            android:textSize="25dp" />


                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_margin="10dp"
                            android:text="@string/featured_companies_description" />


                    </LinearLayout>

                    <androidx.recyclerview.widget.RecyclerView
                        android:id="@+id/featured_recycler"
                        android:layout_width="match_parent"
                        android:layout_height="300dp"
                        android:layout_marginStart="10dp"
                        android:layout_toEndOf="@+id/featured_background"
                        android:background="#fff" />


                </RelativeLayout>


                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:orientation="vertical"
                    android:padding="20dp">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/raleway_bold"
                            android:text="@string/categories"
                            android:textAllCaps="true"
                            android:textColor="#000"
                            android:textSize="20sp" />

                        <TextView
                            android:id="@+id/view_all"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignParentRight="true"
                            android:layout_centerVertical="true"
                            android:onClick="viewAllClicked"
                            android:text="@string/view_all" />


                    </RelativeLayout>


                    <androidx.recyclerview.widget.RecyclerView
                        android:layout_width="match_parent"
                        android:id="@+id/parentLayout"
                        android:layout_height="150dp" />



                </LinearLayout>


            </LinearLayout>
        </ScrollView>


    </LinearLayout>


</androidx.drawerlayout.widget.DrawerLayout>

CategoriesHelperClass.java

    package com.example.tencil.HelperClasses.HomeAdapter;

public class CategoriesHelperClass {
    static int image;
    static String title;

    //SETTER
    public CategoriesHelperClass(int image, String title) {
        this.image = image;
        this.title = title;
    }

    //GETTER
    public static int getImage() {
        return image;
    }

    public static String getTitle() {
        return title;
    }


}

CONSOLE ERROR MESSAGE

    E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tencil, PID: 5226
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.tencil.HelperClasses.HomeAdapter.CategoriesAdapter.onBindViewHolder(CategoriesAdapter.java:55)
    at com.example.tencil.HelperClasses.HomeAdapter.CategoriesAdapter.onBindViewHolder(CategoriesAdapter.java:25)

Any help would be appreciated this has been bugging me for hours.

grabarz121
  • 616
  • 5
  • 13
  • 1
    Welcome to Stack Overflow. From the error message, looks that `holder.parentLayout` is null. Please consider [formatting](https://stackoverflow.com/help/formatting) the error message properly. – ChristianB Jan 04 '21 at 12:17
  • Hi Guys , I'm now getting the following: E/RecyclerView: No adapter attached; skipping layout – Ryan Kimber Jan 04 '21 at 16:39

3 Answers3

0

this is how you would solve this problem from kotlin using callbacks, in java you need to use listeners

in your Activity/Fragment have a function ready to handle the navigation like this

Note that the code below is like a pseudo code and you will have to adjust accordingly

private fun navigateTo(title: String) {
    //handle navigation with the title normally here
    val intent = Intent(this, Category::class.java)
    intent.putExtra("Title", title)
    startActivity(intent)
}

in your Activity's onCreate

val categoriesAdapter = CategoriesAdapter({ title ->
        navigateTo(title)
    })

here's the Adapter and ViewHolder classes

private class CategoriesAdapter(val callBack:(String)-> Unit){
    override fun onCreateViewHolder(): CategoriesViewHolder{
        return CategoriesViewHolder(callBack)
    }
}

private class CategoriesViewHolder(val callBack: (String) -> Unit){
    fun bind(){
        item.setOnClickListener{
            callBack(title)
        }
    }
}

what this does is when you click a certain item, you will get the title and any detail you want from inside the view holder's bind method which will contain only 1 single item inside at any given time, and that will run the method named callBack and sends the title for it back to the adapter, and the adapter does nothing but call the same method again and sends title for it in the Activity, then your Activity will run navigateTo method and do the action required.

in java, you will create a Listener inside your Activity/Fragment and you will use it directly from your ViewHolder if i remember correctly and this will do the same effect

Mahmoud Omara
  • 533
  • 6
  • 22
0

In java, you must cast each element of view to its class, findViewById() returns member of T class, so you will get normal View instead ImageView, TextView etc.

public static class ViewHolder extends RecyclerView.ViewHolder {
    ImageView image;
    TextView title;
    RelativeLayout parentLayout;
    
    public ViewHolder(View itemView) {
        super ( itemView );
        //HOOKS
        image = (ImageView) itemView.findViewById ( R.id.categories_image );
        title = (TextView) itemView.findViewById ( R.id.categories_title );
        parentLayout = (RelativeLayout) itemView.findViewById ( R.id.parentLayout );
    }
}

In addition, if you want to click whole row, you should use holder.itemView.setOnClickListener(). Calling click listener on RelativeLayout will work only, when you touch a free space in your row view, so it may not work each time.

grabarz121
  • 616
  • 5
  • 13
-1

get data from list and set to view (in onBindViewHolder method)

        CategoriesHelperClass item = categories.get(position);

        holder.image.setImageResource ( item.getImage () );
        holder.title.setText ( item.getTitle () );
        holder.itemView.setOnClickListener ( new View.OnClickListener () {

            public void onClick(View v) {
                Log.d (TAG, "OnClick: Clicked on" + mImages.get ( position ));
                Toast.makeText ( mcontext, item.getTitle (), Toast.LENGTH_SHORT ).show ();
            }
        } );

there is no need for this two list, you can handle image and image with categories list

private ArrayList<CategoriesHelperClass> mTitle = new ArrayList<>();
private ArrayList<CategoriesHelperClass> mImages = new ArrayList<>();
miladev95
  • 34
  • 4