英文:
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("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) 
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论