简体   繁体   中英

Custom RecyclerView is null when passing adapter

i'm new to android, but i'm struggling while trying to make work this recycler view.

This is my activity oncreate:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_check_list);
    backToSft = findViewById(R.id.backToSft);
    progressBar = findViewById(R.id.progressBar);
    retrofit = new Retrofit.Builder()
            .baseUrl(RetrofitInterface.API_BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    pref = getSharedPreferences("user_details", MODE_PRIVATE);

    sft = getSharedPreferences("curr_sft", MODE_PRIVATE);
    tagId = sft.getInt("sftId", -1);
    sftName = findViewById(R.id.sftTextName);
    checkListRecycler = findViewById(R.id.recyclerCheckList);
    checkListRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

    if (tagId > 0) {
        sftName.setText(sft.getString("sftTag", "n/d"));
        getCheckData();
    }
}

This is my getCheckData() func:

    private void getCheckData() {
    progressBar.setVisibility(View.VISIBLE);
    try {
        auth += pref.getString("token", null);
        RetrofitInterface service = retrofit.create(RetrofitInterface.class);
        int roleId = pref.getInt("roleId", -1);
        Log.d("ROLE","Is quality oeprator?"+(roleId == UserRole.QUALITY_OPERATOR));
        Call<List<ShortFactoryTagCheck>> call = service.getSFTChecks(tagId, (roleId == UserRole.QUALITY_OPERATOR), auth);
        call.enqueue(new Callback<List<ShortFactoryTagCheck>>() {
            @Override
            public void onResponse(Call<List<ShortFactoryTagCheck>> call, Response<List<ShortFactoryTagCheck>> response) {
                progressBar.setVisibility(View.INVISIBLE);

                try {
                    tagChecks = response.body();
                    if (tagChecks.size() > 0) {
                        Log.d("SFT_OBJ","is SFT Obj NULL? "+(checkListRecycler ==null));
                        
                        adapter = new CheckListRecyclerAdapter(getApplicationContext(),tagChecks);
                        adapter.setClickListener(new CheckListRecyclerAdapter.ItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                Object o = adapter.getItem(position);
                                ShortFactoryTagCheck str = (ShortFactoryTagCheck) o; //As you are using Default String Adapter
                                SharedPreferences.Editor editor = sft.edit();
                                editor.putInt("sftCheckId",str.getId());
                                editor.commit();
                                Intent intent = new Intent(getApplicationContext(), QualityCheckActivity.class);
                                startActivity(intent);
                            }
                        });
                        checkListRecycler.setAdapter(adapter);


                    } else {
                        Intent intent = new Intent(getApplicationContext(), SftDetailActivity.class);
                        startActivity(intent);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("SFT_GSON_ERROR", e.toString());
                }
            }

            @Override
            public void onFailure(Call<List<ShortFactoryTagCheck>> call, Throwable t) {

            }
        });
    } catch (Exception e) {
        Log.d("ERROR_SFT_DETAIL", "Error");
        e.printStackTrace();
    }
}

EDIT: activity_check_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/aptivDark"
tools:context=".CheckListActivity">

<androidx.cardview.widget.CardView
    android:id="@+id/cardView2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:translationY="-10dp"
    app:cardBackgroundColor="@color/aptivOrange"
    app:cardCornerRadius="5dp"
    app:cardElevation="5dp"
    app:contentPadding="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="32dp"
            android:layout_marginRight="32dp"
            android:indeterminate="true"
            android:indeterminateTint="@color/aptivDark"
            android:indeterminateTintMode="src_in"
            android:visibility="invisible"
            app:layout_constraintEnd_toStartOf="@+id/sftTextName"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/sftTextName"
            android:layout_width="wrap_content"
            android:layout_height="0dp"

            android:layout_marginStart="32dp"
            android:layout_marginLeft="32dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:gravity="center"
            android:text="@string/text"
            android:textColor="#FFFFFF"
            android:textSize="36sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/progressBar"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>



</androidx.cardview.widget.CardView>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerCheckList"
    android:layout_width="0dp"
    android:layout_height="450dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/cardView2" />

<Button
    android:id="@+id/backToSft"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="16dp"
    android:layout_marginRight="16dp"
    android:background="@drawable/round_corner_button_danger"
    android:onClick="goToSftDetail"
    android:text="@string/cancel"
    android:textColor="#FFFFFF"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/recyclerCheckList" />
</androidx.constraintlayout.widget.ConstraintLayout>

But when I open this activity, it gives me NullPointerException on checkListRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

I've also tried to clean and rebuild the project, but nothing changed... Also added dependencies to gradle, but still gets error.

Thank you for your help.

EDIT: Error log

2020-10-13 16:22:32.203 5116-5116/com.aptiv.qdc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aptiv.qdc, PID: 5116
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aptiv.qdc/com.aptiv.qdc.CheckListActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2781)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2859)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1592)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6518)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
    at com.aptiv.qdc.CheckListActivity.onCreate(CheckListActivity.java:66)
    at android.app.Activity.performCreate(Activity.java:7034)
    at android.app.Activity.performCreate(Activity.java:7025)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2734)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2859) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1592) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6518) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

below backToSft = findViewById(R.id.backToSft); line put backToSft.setVisibility(View.GONE); - is it also null? maybe there is a chance you have multiple R.layout.activity_check_list files in different density buckets

(copy of comment)

is checkListRecycler RecyclerView variable ? and I think you should cast to RecyclerView like

(RecyclerView) findViewById(R.id.sftTextName)

And change checkListRecycler variable to RecyclerView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM