将数据从 Firebase 检索到 ViewPager - JAVA

Retrieve Data from Firebase to a ViewPager - JAVA

正在从 Firebase 获取数据并将它们附加到适配器return出现此错误

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.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.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)

我创建了一个适配器,并且模型 class 与我在 firebase 的 JSON 格式相匹配。我还为 return 列表创建了一个接口,一旦加载成功,或者 return 如果加载失败则显示错误消息。我不知道我在这里错过了什么。

Firebase JSON: JSON Structure

型号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;
    }

}

适配器 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

在您的 activity onFirebaseLoadSuccess 函数中,您传递的 walkThroughModels 从未初始化 activity.

@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
    adapter = new WalkthroughAdapter(walkThroughModels, this);
    viewPager.setAdapter(adapter);
    //viewPager.setB
}

您必须传递 walkThroughModelsList 而不是它,它具有从 firebase 获取的实际数据。

@Override
public void onFirebaseLoadSuccess(List<WalkThroughModel> walkThroughModelsList) {
    adapter = new WalkthroughAdapter(walkThroughModelsList, this);
    viewPager.setAdapter(adapter);
    //viewPager.setB
}