如何将Firebase数据提取到数组中以进行recyclerview?

时间:2018-04-07 07:18:35

标签: android firebase firebase-realtime-database android-recyclerview

这是我的HomeActivity

package my.unimas.a50200siswa.studentattendancemonitoringsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View; 
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser; 
import com.google.firebase.database.DataSnapshot; 
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity {

String userID;
List<CourseModel> mlist;
TextView btnSignOut, UserName;
RecyclerView courseRecycler;

String CourseCode, CourseName;

/*---- Firebase Database stuff ----*/
FirebaseDatabase mFirebaseDatabase;
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;




@Override
protected void onStart() {

    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}


@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

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

    /*-------Finding View---------*/
    Button btnShow = findViewById(R.id.show);
    btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
    UserName = findViewById(R.id.username);
    courseRecycler = findViewById(R.id.recyclerviewcourse);

    btnSignOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAuth.signOut();
        }

    });


    mAuthListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() == null) {
                startActivity(new Intent(HomeActivity.this, SignInActivity.class));
            }
        }
    };


    /* ----------------- Firebase Elements -----------------*/
    mAuth = FirebaseAuth.getInstance();
    user = mAuth.getCurrentUser();
    userID = user.getUid();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getInstance().getReference();


    UserName.setText(user.getDisplayName());

    /*------------------------------------------------------------------*/


    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            mlist = new ArrayList<CourseModel>();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {

                CourseModel value = dataSnapshot1.getValue(CourseModel.class);
                CourseModel course = new CourseModel();
                String userID = value.getUserId();
                course.setUserId(userID);
                String courseCode = value.getCourseCode();
                course.setCourseCode(courseCode);

                for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
                    CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
                    String courseName = value2.getCourseName();
                    course.setCourseName(courseName);
                    mlist.add(course);

                }

            }

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("Hello", "Failed to read value.", error.toException());
        }
    });




            RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this);
            RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2);
            /// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
            // recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
            courseRecycler.setLayoutManager(recycler);
            courseRecycler.setItemAnimator(new DefaultItemAnimator());
            courseRecycler.setAdapter(recyclerAdapter);


  }
}

这是我的RecyclerViewCourse.class

 package my.unimas.a50200siswa.studentattendancemonitoringsystem;

 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.TextView;

 import java.util.List;

 class RecyclerViewAdapterCourse extends RecyclerView.Adapter<RecyclerViewAdapterCourse.CourseViewHolder> {

 private Context mContext ;
 private List<CourseModel> mlist ;


public RecyclerViewAdapterCourse(List<CourseModel> mData, Context mContext) {
    this.mContext = mContext;
    this.mlist = mData;
}

@Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view =LayoutInflater.from(mContext).inflate(R.layout.item_course,parent,false);
    CourseViewHolder courseViewHolder = new CourseViewHolder(view);

    return courseViewHolder;
}

@Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
    CourseModel courselist = mlist.get(position);
    holder.userID.setText(courselist.getUserId());
    holder.courseCode.setText(courselist.getCourseCode());
    holder.courseName.setText(courselist.getCourseName());
}

@Override
public int getItemCount() {

    int arr = 0;

    try{
        if(mlist.size()==0){
            arr = 0;
        }
        else{
            arr=mlist.size();
        }

    }catch (Exception e){
    }
    return arr;
}

class CourseViewHolder extends RecyclerView.ViewHolder{
    TextView userID,courseCode,courseName;


    public CourseViewHolder(View itemView) {
        super(itemView);
        userID = (TextView) itemView.findViewById(R.id.userid);
        courseCode= (TextView) itemView.findViewById(R.id.coursecode);
        courseName= (TextView) itemView.findViewById(R.id.coursename);
    }
}


}

这是我的CourseModel.class

package my.unimas.a50200siswa.studentattendancemonitoringsystem;


public class CourseModel {

public String UserId, CourseCode, CourseName;

public String getUserId() {
    return UserId;
}

public String getCourseCode() {
    return CourseCode;
}

public String getCourseName() {
    return CourseName;
}


public void setUserId(String userid) {
    this.UserId = userid;
}

public void setCourseCode(String coursecode) {
    this.CourseCode = coursecode;
}

public void setCourseName(String coursename) {
    this.CourseCode = coursename;
}


}

我希望数组列表如下:

{"***", "TMI4013", "System Programming"}
{"***", "TMI4033", "LogicProgramming"}

Image

我对阵列中的firebase数据检索并不熟悉。我在堆栈中尝试了很多答案。没人工作。在某些答案中,有时它会在一段时间后显示数据,然后在实时数据库中数据被删除,我甚至不理解为什么。

我没有提供XML文件,因为我尝试使用本地文件并在HomeActivity中生成数组,并且它工作得很好。

    mlist = new ArrayList<>();
    mlist.add(new CourseModel("012223","TMN4013","System Programming"));
    mlist.add(new CourseModel("34566","TMN4013","System Programming"));
    RecyclerView myrv = (RecyclerView) findViewById(R.id.recyclerview_id);
    RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,mlist);
    myrv.setLayoutManager(new GridLayoutManager(this,3));
    myrv.setAdapter(myAdapter);

1 个答案:

答案 0 :(得分:0)

从firebase检索数据并将列表转换为像这样的数组

for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) { 
    CourseModel value = dataSnapshot1.getValue(CourseModel.class); 
    CourseModel course = new CourseModel(); 
    String userID = value.getUserId(); course.setUserId(userID); 
    String courseCode = value.getCourseCode();
    course.setCourseCode(courseCode);
    for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) { 
        CourseModel value2 = dataSnapshot2.getValue(CourseModel.class); 
        String courseName = value2.getCourseName(); 
        course.setCourseName(courseName);
        mlist.add(course);

    } 

}

  CourseModel[] array = mlist.toArray(new CourseModel[mlist.size()]);

修改

像这样更改你的适配器

RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, array);

将recyclerView的构造函数更改为CourseModel数组

public RecyclerViewAdapterCourse(CourseModel[] mData, Context mContext) {
     this.mContext = mContext; 
     this.mArray = mData; 
  } 


@Override 
public void onBindViewHolder(CourseViewHolder holder, int position) { 
    CourseModel courselist = marray[position];
    holder.userID.setText(courselist.getUserId());
    holder.courseCode.setText(courselist.getCourseCode());
    holder.courseName.setText(courselist.getCourseName());
 }