自定义的 RecyclerView 在传递适配器时为空。

huangapple go评论63阅读模式
英文:

Custom RecyclerView is null when passing adapter

问题

以下是您提供的代码的翻译部分:

我是Android新手但在尝试使这个RecyclerView工作时遇到了困难

这是我的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();
    }
}

这是我的`getCheckData`方法

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", "是否质量操作员?" + (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", "SFT对象是否为空?" + (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; //因为您使用了默认的String适配器
                                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", "错误");
        e.printStackTrace();
    }
}

activity_check_list.xml的部分不需要翻译。如果您需要更多帮助或有其他问题,请随时提出。

英文:

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(&quot;user_details&quot;, MODE_PRIVATE);
sft = getSharedPreferences(&quot;curr_sft&quot;, MODE_PRIVATE);
tagId = sft.getInt(&quot;sftId&quot;, -1);
sftName = findViewById(R.id.sftTextName);
checkListRecycler = findViewById(R.id.recyclerCheckList);
checkListRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
if (tagId &gt; 0) {
sftName.setText(sft.getString(&quot;sftTag&quot;, &quot;n/d&quot;));
getCheckData();
}
}

This is my getCheckData() func:

    private void getCheckData() {
progressBar.setVisibility(View.VISIBLE);
try {
auth += pref.getString(&quot;token&quot;, null);
RetrofitInterface service = retrofit.create(RetrofitInterface.class);
int roleId = pref.getInt(&quot;roleId&quot;, -1);
Log.d(&quot;ROLE&quot;,&quot;Is quality oeprator?&quot;+(roleId == UserRole.QUALITY_OPERATOR));
Call&lt;List&lt;ShortFactoryTagCheck&gt;&gt; call = service.getSFTChecks(tagId, (roleId == UserRole.QUALITY_OPERATOR), auth);
call.enqueue(new Callback&lt;List&lt;ShortFactoryTagCheck&gt;&gt;() {
@Override
public void onResponse(Call&lt;List&lt;ShortFactoryTagCheck&gt;&gt; call, Response&lt;List&lt;ShortFactoryTagCheck&gt;&gt; response) {
progressBar.setVisibility(View.INVISIBLE);
try {
tagChecks = response.body();
if (tagChecks.size() &gt; 0) {
Log.d(&quot;SFT_OBJ&quot;,&quot;is SFT Obj NULL? &quot;+(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(&quot;sftCheckId&quot;,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(&quot;SFT_GSON_ERROR&quot;, e.toString());
}
}
@Override
public void onFailure(Call&lt;List&lt;ShortFactoryTagCheck&gt;&gt; call, Throwable t) {
}
});
} catch (Exception e) {
Log.d(&quot;ERROR_SFT_DETAIL&quot;, &quot;Error&quot;);
e.printStackTrace();
}
}

EDIT:
activity_check_list.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:background=&quot;@color/aptivDark&quot;
tools:context=&quot;.CheckListActivity&quot;&gt;
&lt;androidx.cardview.widget.CardView
android:id=&quot;@+id/cardView2&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;8dp&quot;
android:layout_marginEnd=&quot;8dp&quot;
android:translationY=&quot;-10dp&quot;
app:cardBackgroundColor=&quot;@color/aptivOrange&quot;
app:cardCornerRadius=&quot;5dp&quot;
app:cardElevation=&quot;5dp&quot;
app:contentPadding=&quot;10dp&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ProgressBar
android:id=&quot;@+id/progressBar&quot;
style=&quot;?android:attr/progressBarStyle&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginEnd=&quot;32dp&quot;
android:layout_marginRight=&quot;32dp&quot;
android:indeterminate=&quot;true&quot;
android:indeterminateTint=&quot;@color/aptivDark&quot;
android:indeterminateTintMode=&quot;src_in&quot;
android:visibility=&quot;invisible&quot;
app:layout_constraintEnd_toStartOf=&quot;@+id/sftTextName&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/sftTextName&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;0dp&quot;
android:layout_marginStart=&quot;32dp&quot;
android:layout_marginLeft=&quot;32dp&quot;
android:layout_marginEnd=&quot;8dp&quot;
android:layout_marginRight=&quot;8dp&quot;
android:gravity=&quot;center&quot;
android:text=&quot;@string/text&quot;
android:textColor=&quot;#FFFFFF&quot;
android:textSize=&quot;36sp&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toEndOf=&quot;@+id/progressBar&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
&lt;/androidx.cardview.widget.CardView&gt;
&lt;androidx.recyclerview.widget.RecyclerView
android:id=&quot;@+id/recyclerCheckList&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;450dp&quot;
android:layout_marginStart=&quot;8dp&quot;
android:layout_marginLeft=&quot;8dp&quot;
android:layout_marginTop=&quot;8dp&quot;
android:layout_marginEnd=&quot;8dp&quot;
android:layout_marginRight=&quot;8dp&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.0&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/cardView2&quot; /&gt;
&lt;Button
android:id=&quot;@+id/backToSft&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;50dp&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginLeft=&quot;16dp&quot;
android:layout_marginTop=&quot;8dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:layout_marginRight=&quot;16dp&quot;
android:background=&quot;@drawable/round_corner_button_danger&quot;
android:onClick=&quot;goToSftDetail&quot;
android:text=&quot;@string/cancel&quot;
android:textColor=&quot;#FFFFFF&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/recyclerCheckList&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

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 &#39;void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)&#39; 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 &#39;void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)&#39; 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)&#160;
at android.app.ActivityThread.-wrap11(Unknown Source:0)&#160;
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1592)&#160;
at android.os.Handler.dispatchMessage(Handler.java:106)&#160;
at android.os.Looper.loop(Looper.java:164)&#160;
at android.app.ActivityThread.main(ActivityThread.java:6518)&#160;
at java.lang.reflect.Method.invoke(Native Method)&#160;
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)&#160;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)&#160;

答案1

得分: 1

backToSft = findViewById(R.id.backToSft); 行下添加 backToSft.setVisibility(View.GONE); - 它也是 null 吗?也许你有多个不同密度桶中的 R.layout.activity_check_list 文件。

英文:

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)

答案2

得分: 0

checkListRecycler 一个 RecyclerView 变量吗?我认为你应该将它强制转换为 RecyclerView,就像这样:

(RecyclerView) findViewById(R.id.sftTextName)

然后将 checkListRecycler 变量改为 RecyclerView。

英文:

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

(RecyclerView) findViewById(R.id.sftTextName)

And change checkListRecycler variable to RecyclerView

huangapple
  • 本文由 发表于 2020年10月13日 17:41:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64332658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定