英文:
Retrieve Data from Firebase to a ViewPager - JAVA
问题
从Firebase获取数据并将它们附加到适配器时出现以下错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.shaiicodez.surface, PID: 16110
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.shaiicodez.surface.adapter.WalkthroughAdapter.getCount(WalkthroughAdapter.java:34)
at androidx.viewpager.widget.ViewPager.setAdapter(ViewPager.java:532)
at com.shaiicodez.surface.WalkthroughActivity.onFirebaseLoadSuccess(WalkthroughActivity.java:100)
at com.shaiicodez.surface.WalkthroughActivity$2.onDataChange(WalkthroughActivity.java:87)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8125)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
我已经创建了适配器和与我的Firebase JSON格式匹配的模型类。我还创建了一个接口,在加载成功时返回列表,或在加载失败时返回错误消息。我无法弄清楚我在这里漏掉了什么。
Firebase JSON:
JSON 结构
模型类: WalkthoughModel.java
public class WalkThroughModel {
// ...(与您提供的代码相同)
}
适配器类: WalkthroughAdapter.java
public class WalkthroughAdapter extends PagerAdapter {
// ...(与您提供的代码相同)
}
活动类: WalkthroughActivity.java
public class WalkthroughActivity extends AppCompatActivity implements IFirebaseLoadDone {
// ...(与您提供的代码相同)
}
英文:
Fetching the data from Firebase and attaching them to an adapter returns this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.shaiicodez.surface, PID: 16110
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.shaiicodez.surface.adapter.WalkthroughAdapter.getCount(WalkthroughAdapter.java:34)
at androidx.viewpager.widget.ViewPager.setAdapter(ViewPager.java:532)
at com.shaiicodez.surface.WalkthroughActivity.onFirebaseLoadSuccess(WalkthroughActivity.java:100)
at com.shaiicodez.surface.WalkthroughActivity$2.onDataChange(WalkthroughActivity.java:87)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8125)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
I have created an Adapter, and Model class that matches my JSON format at firebase. I have also created an Interface to return the list once the load is successfull, or return an error message if loading is failed. I couldn't figure out what i missed here.
Firebase JSON:
JSON Structure
Model class: WalkthoughModel.java
public class WalkThroughModel {
private String image;
private String title;
private String description;
public WalkThroughModel() {
}
public WalkThroughModel(String image, String title, String description) {
this.image = image;
this.title = title;
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Adapter Class: WalkthroughAdapter.java
public class WalkthroughAdapter extends PagerAdapter {
private List<WalkThroughModel> walkThroughModels;
private LayoutInflater layoutInflater;
private Context context;
public WalkthroughAdapter(List<WalkThroughModel> walkThroughModels, Context context) {
this.walkThroughModels = walkThroughModels;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return walkThroughModels.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View)object);
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, final int position) {
//inflate View
View view = layoutInflater.inflate(R.layout.item_walkthrough, container, false);
//Views
ImageView imageView = view.findViewById(R.id.image);
TextView title = view.findViewById(R.id.title);
TextView desc = view.findViewById(R.id.desc);
//set data
Picasso.with(context).load(walkThroughModels.get(position).getImage()).into(imageView);
title.setText(walkThroughModels.get(position).getTitle());
desc.setText(walkThroughModels.get(position).getDescription());
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Intent intent = new Intent(walkthroughs, DetailActivity.class);
//intent.putExtra("param", models.get(position).getTitle());
//context.startActivity(intent);
// finish();
Toast.makeText(context, "Yay!!!", Toast.LENGTH_SHORT).show();
}
});
container.addView(view);
return view;
}
}
Activity Class: WalkthroughActivity.java
public class WalkthroughActivity extends AppCompatActivity implements IFirebaseLoadDone {
//ui
ViewPager viewPager;
WalkthroughAdapter adapter;
Button btnGo;
List<WalkThroughModel> walkThroughModels;
Integer[] colors = null;
ArgbEvaluator argbEvaluator = new ArgbEvaluator();
//firebase
DatabaseReference firebaseDatabase;
IFirebaseLoadDone iFirebaseLoadDone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walkthrough);
//init firebase
firebaseDatabase = FirebaseDatabase.getInstance().getReference(Common.WALK_THROUGH_REF);
//walkthroughRef = firebaseDatabase.getReference(Common.WALK_THROUGH_REF);
//event init
iFirebaseLoadDone = this;
loadWalkthrough();
viewPager = findViewById(R.id.walkViewPager);
btnGo = findViewById(R.id.btn_go);
btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent goSignUp = new Intent(WalkthroughActivity.this, SignInActivity.class);
startActivity(goSignUp);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
//finish();
}
});
}//end onCreate
private void loadWalkthrough() {
firebaseDatabase.addValueEventListener(new ValueEventListener() {
List<WalkThroughModel> walkThroughModelList = new ArrayList<>();
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapShot : snapshot.getChildren())
walkThroughModelList.add(postSnapShot.getValue(WalkThroughModel.class));
iFirebaseLoadDone.onFirebaseLoadSuccess(walkThroughModelList);
}//end onDataChange
@Override
public void onCancelled(@NonNull DatabaseError error) {
iFirebaseLoadDone.onFirebaseLoadFailed(error.getMessage());
}//end onCancelled
});
}//end loadWalkthrough
@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
adapter = new WalkthroughAdapter(walkThroughModels, this);
viewPager.setAdapter(adapter);
//viewPager.setB
}
@Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
}
}//end class
答案1
得分: 1
在你的 activity 的 onFirebaseLoadSuccess 函数中,你传递了一个未初始化的 walkThroughModels 参数。
@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
adapter = new WalkthroughAdapter(walkThroughModels, this);
viewPager.setAdapter(adapter);
//viewPager.setB
}
而你实际上应该传递包含从 Firebase 获取的实际数据的 walkThroughModelsList 参数。
@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
adapter = new WalkthroughAdapter(walkThroughModelsList, this);
viewPager.setAdapter(adapter);
//viewPager.setB
}
英文:
In you activity onFirebaseLoadSuccess function you are passing walkThroughModels which is never initialised the the activity.
@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
adapter = new WalkthroughAdapter(walkThroughModels, this);
viewPager.setAdapter(adapter);
//viewPager.setB
}
instead of which you have to pass walkThroughModelsList which has actual data fetched from firebase.
@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
adapter = new WalkthroughAdapter(walkThroughModelsList, this);
viewPager.setAdapter(adapter);
//viewPager.setB
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论