Почему мой адаптер внутри утилита просмотра не отображается? - PullRequest
0 голосов
/ 03 декабря 2018

Я хочу отобразить историю регистрации в parentHomeActivity , где все эти данные будут взяты в базу данных firebase.Я создал кодировку адаптера, а также Recent_registration_list_layout.xml для отображения только 2 атрибутов: -

  1. Имя студента (полное имя)

  2. Имя обучения, которое было зарегистрировано (tuitionName).

Нет красной ошибки, сбоя или какой-либо регистрации.Проблема, с которой я столкнулся, заключалась в том, что мой адаптер не отображался в моих приложениях.Очень надеюсь, что кто-то может научить меня, новичка в Android Studio.Заранее спасибо.

Структура базы данных показана ниже, я хочу отображать только атрибут красного круга: -

enter image description here

Кодировка адаптера показана ниже: -

public class RegistrationHistoryAdapter extends RecyclerView.Adapter<RegistrationHistoryAdapter.ChildrenViewHolder>
{
    private Context mCtx;
    private List<StudentRegistration> childrenList;

public RegistrationHistoryAdapter(Context mCtx, List<StudentRegistration> childrenList)
{
    this.mCtx = mCtx;
    this.childrenList = childrenList;
}

@NonNull
@Override
public ChildrenViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.recent_registration_list_layout, parent, false);
    return new ChildrenViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final ChildrenViewHolder holder, final int position)
{
    final StudentRegistration studentRegistration = childrenList.get(holder.getAdapterPosition());
    holder.tuitioNameView.setText(studentRegistration.getTuitioname());
    holder.studNameView.setText(studentRegistration.getFullname());
}

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

class ChildrenViewHolder extends RecyclerView.ViewHolder
{
    TextView tuitioNameView, studNameView;
    CardView childrenLayout;

    public ChildrenViewHolder(View itemView)
    {
        super(itemView);
        tuitioNameView = itemView.findViewById(R.id.tvTuitionName);
        studNameView = itemView.findViewById(R.id.tvFullName);
        childrenLayout = itemView.findViewById(R.id.cvChildren);
    }
}
}

parentHomeActivity показана ниже: -

databaseReference.child("Student Registration").child(mAuth.getUid()).addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            //Iterating through all the values in database
            mChildrenList = new ArrayList<>();
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                StudentRegistration studentRegistration = postSnapshot.getValue(StudentRegistration.class);
                mChildrenList.add(0, studentRegistration);
            }

            //Creating adapter
            mAdapters = new RegistrationHistoryAdapter(getApplicationContext(), mChildrenList);

            //Adding adapter to recyclerview
            mRecyclerView.setAdapter(mAdapters);
            mAdapters.notifyItemInserted(0);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError)
        {

        }
    });

    //other method
    mRecyclerView.setHasFixedSize(true); //set fixed size for element in recycler view
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

Recycleviewмакет в XML показывает ниже: -

<android.support.v7.widget.RecyclerView
        android:id="@+id/rvChildren"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/roundedbutton8"/>

Ответы [ 3 ]

0 голосов
/ 03 декабря 2018

Изменение с

for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                StudentRegistration studentRegistration = postSnapshot.getValue(StudentRegistration.class);
                mChildrenList.add(0, studentRegistration);
            }

На

for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                StudentRegistration studentRegistration = postSnapshot.getValue(StudentRegistration.class);
                mChildrenList.add(studentRegistration);
            }

И с

mAdapters.notifyItemInserted (0);

На

mAdapters.notifyDataSetChanged ();

0 голосов
/ 03 декабря 2018

Вы должны хранить данные таким образом

    String current_user = FirebaseAuth.getInstance().getCurrentUser().getUid();
    mDatabase.child("Student Registration").child(current_user).child(uid).setValue(studentRegistration).addOnCompleteListener(new OnCompleteListener<Void>()
    {
        @Override
        public void onComplete(@NonNull Task<Void> task)
        {
            if(task.isSuccessful())
            {
                Toast.makeText(RegisterActivity.this, "Successfully registered!", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(RegisterActivity.this, FinishActivity.class));
                finish();
            }

            else
            {
                Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
            }
            loadingBar.dismiss();
        }
    });

Затем для извлечения данных.используйте этот код

    String current_user = FirebaseAuth.getInstance().getCurrentUser().getUid();


    databaseReference.child("Student Registration").child(current_user).addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            //Iterating through all the values in database
            mChildrenList = new ArrayList<>();
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                StudentRegistration studentRegistration = postSnapshot.getValue(StudentRegistration.class);
                mChildrenList.add(studentRegistration);
            }

            //Creating adapter
            mAdapters = new RegistrationHistoryAdapter(getApplicationContext(), mChildrenList);

            //Adding adapter to recyclerview
            mRecyclerView.setAdapter(mAdapters);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError)
        {

        }
    });

В вашем адаптере измените onBindViewHolder с этим

@Override
public void onBindViewHolder(@NonNull final ChildrenViewHolder holder, final int position)
{
    holder.tuitioNameView.setText(childrenList.get(holder.getAdapterPosition()).getTuitioname());
    holder.studNameView.setText(childrenList.get(holder.getAdapterPosition()).getFullname());
}
0 голосов
/ 03 декабря 2018

Получить данные о базе данных огня с помощью этого метода:

ref.child("Student Registeration").addListenerForSingleValueEvent(new 
  ValueEventListener() {
 @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
     if(dataSnapshot.getValue != null) {
       for(DataSnapshot ds : dataSnapshot.getChildren()) {
            //get your object data from ds and add it to array list
        }
  //set adapter now
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
  // ...
}
});
...