1

This is my 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);


  }
}

This is My 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);
    }
}


}

This is My 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;
}


}

I want the array list like:

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

Image

I am not really experienced with firebase data retrieval in array. I tried many answers posted in stack. none worked. in some answers, sometime it shows data after a while and then in the realtime database the data get removed, i don't even understand why.

I did not provide the XML files since I tried with local file and generating array in HomeActivity and it worked perfectly.

    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);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • please add a screenshot of your firebase db – Nuwan Alawatta Apr 07 '18 at 07:22
  • @Nuwan94 i already addded. please click on the link saying "I want the array list like {........" –  Apr 07 '18 at 07:33
  • you need to fetch data from firebase and show it on recyclerView? am I right? – Sarasa Gunawardhana Apr 07 '18 at 08:09
  • @SarasaGunawardhana yes.. RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this); RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2); courseRecycler.setLayoutManager(recycler); courseRecycler.setItemAnimator(new DefaultItemAnimator()); courseRecycler.setAdapter(recyclerAdapter); –  Apr 07 '18 at 08:37
  • If you are interested, **[this](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849)** is how you can retrieve data from a Firebase Realtime database and display it in a `RecyclerView` using `FirebaseRecyclerAdapter`. – Alex Mamo Apr 07 '18 at 09:50

1 Answers1

0

Retrieve data from firebase and convert list into array like this

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()]);

EDIT:

Change your adapter like this

RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, array);

Change the constructor of recyclerView to CourseModel array

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());
 }
Fazal Hussain
  • 1,129
  • 12
  • 28
  • Thank you for your reply.. it is showing error of finding odject where it should find CourseModel[]. how can i then pass it to my context in recyclerview? –  Apr 07 '18 at 08:10
  • Hussein thank you again shows same error even after the correction according to your suggestion. –  Apr 07 '18 at 11:26
  • 1
    error: incompatible types: Object[] cannot be converted to CourseModel[] error: incompatible types: HomeActivity cannot be converted to CourseModel[] –  Apr 07 '18 at 11:42
  • Check the edited answer. This will solve your problem – Fazal Hussain Apr 07 '18 at 11:53