从firebase数据库中检索数据并存储在数组列表中

时间:2017-01-11 10:04:33

标签: java android arraylist firebase firebase-realtime-database

我正在尝试以Android应用程序的形式创建一个小型课程聚合器程序。

我的课程都存储在Firebase实时数据库中,可以从firebase控制台查看,一切正常。

问题是我编写了一个java方法来连接数据库,从数据库中检索数据,将数据转换为自定义Java对象Course,将其附加到另一个自定义Java对象{{1然后将CourseCardModel对象保存到ArrayList中。

成功建立了与数据库的连接,并且它生成的快照包含正确的信息,我已通过循环快照并成功打印每个CourseCardModel对象的变量Course Name来验证这些信息。问题是当方法完成时,由于某种原因,arrayList返回为空,即使在整个快照迭代中检查ArrayList的大小时,我也可以看到添加了Course个对象。

如果有任何人帮助解决这个问题,我将非常感谢,我对Firebase来说还是新手。

GenerateCourses()方法

CardModel

LOGCAT输出

private ArrayList<CourseCardModel> generateCourseCards() {

    courseCardModelList = new ArrayList<CourseCardModel>();
    cardModel = new CourseCardModel();

    dbref =  FirebaseDatabase.getInstance().getReference().child("courses");


    // Retrieve the course data from firebase db and cast as Course object
    dbref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Log.e("Count " ,"" + snapshot.getChildrenCount());
            for (DataSnapshot postSnapshot: snapshot.getChildren()) {

                c = postSnapshot.getValue(Course.class);
                System.out.println("COURSE INFO: " + c.getCourseName());

                cardModel.setCourse(c);

                courseCardModelList.add(cardModel);

                System.out.println("COURSE CARD MODEL LIST SIZE: " + courseCardModelList.size());

            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("The read failed: ", databaseError.getMessage());
        }

    });

    System.out.print("END OF METHOD ARRAY SIZE CHECK: " + courseCardModelList.size());

    return courseCardModelList;

}

2 个答案:

答案 0 :(得分:3)

调用dbref.addValueEventListener()的结果会在onDataChange回调中异步返回...这很可能在您从该方法返回时发生,这就是为什么{{1 }} 是空的。您需要相应地构建逻辑。

答案 1 :(得分:-1)

[enter image description here] [1

]这是在Activity Class中,下面的代码可以帮助您从数据库中检索单个值,也可以检索Arraylist中的所有数据和存储,以及带有Key值对的Hashmap在注释行中显示。在此之后,您可以根据需要填写Recyclerview或Listview中的所有检索数据:

public class NavigationActivity extends AppCompatActivity{
    CourseListNewAdapter courseListNewAdapter;
    private DatabaseReference mDatabase;
    private ArrayList<Course> userCourseDetailsesList;
    private RecyclerView rv_course_detail;
    @Override
        protected void onStart() {
            super.onStart();
            mAuth.addAuthStateListener(mAuthListener);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_navigation);

    initializeAuthListener();

            mDatabase = FirebaseDatabase.getInstance().getReference();

rv_course_detail = (RecyclerView) findViewById(R.id.rv_course_detail);
    }

    private void initializeAuthListener() {
            mAuth = FirebaseAuth.getInstance();
            mAuthListener = new FirebaseAuth.AuthStateListener() {
                @Override
                public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    firebaseUser = firebaseAuth.getInstance().getCurrentUser();
                    try {
                        if (firebaseAuth != null) {
                            loadUserDetails();
                            Log.d("@@@@", "thread:signed_in:" + firebaseUser.getUid());
                        } else {
                            Log.d("@@@@", "thread:signed_out");
                            Intent login = new Intent(NavigationActivity.this, LoginActivity.class);
                            startActivity(login);
                            finish();
                        }
                    }catch (Exception e){
                        Intent login = new Intent(NavigationActivity.this, LoginActivity.class);
                        startActivity(login);
                        finish();
                    }

                }
            };
            mAuth.addAuthStateListener(mAuthListener);
        }

    private void loadUserDetails() {
            DatabaseReference userReference = mDatabase
                    .child("users").child(firebaseUser.getUid());

    //        displayUserDetails(userReference);
            userReference.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    user = dataSnapshot.getValue(User.class);

                    tv_user_name.setText(user.getDisplayName());
                    tv_user_email_nav.setText(user.getEmail());

                    Glide.with(NavigationActivity.this)
                            .load(user.getPhotoUrl())
                            .placeholder(R.mipmap.profile)
                            .centerCrop()
                            .dontAnimate()
                            .bitmapTransform(new CropCircleTransformation(NavigationActivity.this))
                            .into(iv_user_image);

                    loadUserCourseList();
    //                String PhoneNumber = user.getPhoneNumber();
    //                Log.e("UserPhone",PhoneNumber);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
    //                Toast.makeText(ThreadActivity.this, R.string.error_loading_user, Toast.LENGTH_SHORT).show();
    //                finish();
                }
            });
        }

    private void loadUserCourseList(){

            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Course").child(firebaseUser.getUid());
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    userCourseDetailsesList = new ArrayList<>();
    //                AlluserCourseDetailsesList = new ArrayList<>();
                    if(dataSnapshot.exists())
                    {
                        for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
                        {
    //                        if (firebaseUser.getUid().equals(postSnapShot.getKey())) {
                                Course userCourseDetails = postSnapShot.getValue(UserCourseDetails.class);
                                userCourseDetailsesList.add(new UserCourseDetails(userCourseDetails.getCourse_type(), userCourseDetails.getCourse_id(), userCourseDetails.getCourse_Pic_url()));
                            }
                        }

                        courseListNewAdapter =  CourseListNewAdapter(NavigationActivity.this, userCourseDetailsesList);
                        RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(NavigationActivity.this);
                        rv_Course_detail.setLayoutManager(layoutmanager);
                        rv_Course_detail.setItemAnimator( new DefaultItemAnimator());
                        rv_Course_detail.setAdapter(CourseListNewAdapter);

    //                    Constants.AllCourse  = new ArrayList<HashMap<String, String>>();
    //                    HashMap<String, String> map = new HashMap<String, String>();
    //
    //                    map.put("course_id",userCourseDetails.getCourse_id());
    //                    map.put("course_Pic_url", userCourseDetails.getCourse_Pic_url());
    //                    map.put("course_type", userCourseDetails.getCourse_type());
    //
    //                    Constants.AllCourseList.add(map);

    //                    courseListAdapter = new CourseListAdapter(NavigationActivity.this, userCourseDetailsesList);
    //                    lv_Course_detail.setAdapter(courseListAdapter);
                    }else{
                        Intent i = new Intent(NavigationActivity.this, AddCourseActivity.class);
                        startActivity(i);
                        finish();

    //                    NavigationActivity.this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_in_left);
                    }
                    Log.e("Course List size",""+userCourseDetailsesList.size());
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

    }

}

Recycler Adapter:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import java.util.ArrayList;

public class CourseListNewAdapter extends RecyclerView.Adapter<CourseListNewAdapter.MyViewHolder> {
    Context context;
    ArrayList<UserCourseDetails> userCourseDetailses;

    public CourseListNewAdapter(Context context, ArrayList<UserCourseDetails> userCourseDetailses) {
        this.context = context;
        this.userCourseDetailses = userCourseDetailses;
    }


    // Provide a suitable constructor (depends on the kind of dataset)

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView iv_course_photo;
        public TextView tv_course_type;
        public TextView tv_course_id;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv_course_photo = (ImageView) itemView.findViewById(R.id.iv_course_photo);
            tv_course_type = (TextView) itemView.findViewById(R.id.tv_course_type);
            tv_course_id = (TextView) itemView.findViewById(R.id.tv_course_id);
        }
    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_user_Course_list, parent, false);
        return new MyViewHolder(view);
    }

    MyViewHolder holderView;

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holderView = holder;

        try {
            if (userCourseDetailses.size() > 0) {

                final UserCourseDetails s = userCourseDetailses.get(position);
                holder.tv_course_type.setText(s.getCourse_type());
                holder.tv_course_number.setText(s.getCourse_id());

                // Loading Course image
                Glide.with(context).load(s.getCourse_Pic_url())
                        .crossFade()
                        .thumbnail(0.5f)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.plaeholder_item)
                        .listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                holder.iv_course_photo.setImageDrawable(resource);
                                return false;
                            }
                        })
                        .into(holder.iv_course_photo);
            }
        } catch (Exception e) {
        }

    }

    @Override
    public int getItemCount() {
        return userCourseDetailses.size();
    }

    public boolean isEmpty() {
        return getItemCount() == 0;
    }
}

Listview适配器:

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import java.util.ArrayList;
import java.util.HashMap;

public class CourseListAdapter  extends BaseAdapter {
    Context context;
    ArrayList<UserCourseDetails> userCourseDetailses;

    ImageView iv_number_plate_photo;
    public CourseListAdapter(Context c, ArrayList<UserCourseDetails> userCourseDetailses) {
        this.context = c;
        this.userCourseDetailses = userCourseDetailses;
    }

    @Override
    public int getCount() {
        return userCourseDetailses.size();
    }

    @Override
    public Object getItem(int pos) {
        return userCourseDetailses.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        if(convertView==null)
        {
            convertView= LayoutInflater.from(context).inflate(R.layout.adapter_user_Course_list,viewGroup,false);
        }

        iv_number_plate_photo = (ImageView) convertView.findViewById(R.id.iv_number_plate_photo);
        TextView tv_Course_brand= (TextView) convertView.findViewById(R.id.tv_Course_brand);
        TextView tv_Course_type= (TextView) convertView.findViewById(R.id.tv_Course_type);
        TextView tv_Course_number= (TextView) convertView.findViewById(R.id.tv_Course_number);

        final UserCourseDetails s= (UserCourseDetails) this.getItem(position);

        tv_Course_brand.setText(s.getCourse_brand());
        tv_Course_type.setText(s.getCourse_type());
        tv_Course_number.setText(s.getCourse_id());

        // Loading profile image
        Glide.with(context).load(s.getCourse_number_plate_url())
                .crossFade()
                .thumbnail(0.5f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.plaeholder_item)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        iv_number_plate_photo.setImageDrawable(resource);
                        return false;
                    }
                })
                .into(iv_number_plate_photo);
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //OPEN DETAIL
//                openDetailActivity(s.getName(),s.getDescription(),s.getPropellant());
            }
        });

        return convertView;
    }
}