Ошибка: адаптер не подключен, пропускает макет к классу при использовании recyclerview и firebase - PullRequest
0 голосов
/ 28 апреля 2020

Я много пытался исправить это, но не смог. он говорит, что мой адаптер не подключен. но когда я объявляю адаптер в onCreate и запускаю, он показывает пустое действие для следующего кода:

mainactivity. java

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    DatabaseReference collegereference;
    private CollegeAdapter collegeAdapter;
    List<College> collegelist = new List<College>(); //lot of functions under this which i didnt put in this question

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler);
        collegereference = FirebaseDatabase.getInstance().getReference().child("colleges");         
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        collegeAdapter = new CollegeAdapter(MainActivity.this,collegelist);
        //initialised adapter after getting 'adapter not attached, skipping activity'
        //i am not getting this error anymore but when i run, a blank acitvity pops up
        recyclerView.setAdapter(collegeAdapter);
        collegereference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
                {
                    collegelist.add(dataSnapshot1.getValue(College.class));
                }
                recyclerView.setAdapter(collegeAdapter);
                collegeAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(MainActivity.this, "unsuccessful", Toast.LENGTH_SHORT).show();
            }
        });

    }

}

это мой класс адаптера:

CollegeAdapter. java

public class CollegeAdapter extends RecyclerView.Adapter<CollegeAdapter.CollegeViewHolder>  {

    Context c;
    private List<College> collegelist;

    public CollegeAdapter(Context c, List<College> collegelist)
    {
        LayoutInflater manager = LayoutInflater.from(c);
        this.c = c;
        this.collegelist = collegelist;
    }

    @NonNull
    @Override
    public CollegeAdapter.CollegeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        return new CollegeViewHolder(LayoutInflater.from(c).inflate(R.layout.collegecardview,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull CollegeAdapter.CollegeViewHolder holder, int position) 
    {
        holder.collegename.setText(collegelist.get(position).getName());
        holder.rating.setText(collegelist.get(position).getRating());
    }

    @Override
    public int getItemCount() 
    {
        return collegelist.size(); //points to null, when there was no adapter initialised in onCreate
    }

    public class CollegeViewHolder extends RecyclerView.ViewHolder 
    {
        TextView collegename,rating;

        public CollegeViewHolder(@NonNull View itemView) 
        {
            super(itemView);
            collegename = itemView.findViewById(R.id.collegename);
            rating = itemView.findViewById(R.id.rating);
        }
    }
}

мой макет просмотра карты:

mainacctivity. xml

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="LinearLayoutManager"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

моя активность просмотра карты: Collegecardview. xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="College Name"
        android:textSize="15sp"
        android:textStyle="bold"/>
    <TextView
        android:id="@+id/collegename"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Rating"
        android:textStyle="bold"
        android:textSize="15sp"/>
    <TextView
        android:id="@+id/rating"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/collegeimage"/>
</LinearLayout>

И теперь я получаю эту ошибку:

04-28 06:27:37.832 15830-15830/? I/art: Not late-enabling -Xcheck:jni (already on)
04-28 06:27:37.896 15830-15830/? W/System: ClassLoader referenced unknown path: /data/app/com.example.collegefirebase-2/lib/x86_64
04-28 06:27:37.917 15830-15830/com.example.collegefirebase I/FirebaseInitProvider: FirebaseApp initialization successful
04-28 06:27:37.940 15830-15830/com.example.collegefirebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-28 06:27:38.006 15830-15830/com.example.collegefirebase I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-28 06:27:38.006 15830-15830/com.example.collegefirebase I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-28 06:27:38.239 15830-15853/com.example.collegefirebase D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-28 06:27:38.335 15830-15853/com.example.collegefirebase I/OpenGLRenderer: Initialized EGL, version 1.4
04-28 06:27:38.339 15830-15853/com.example.collegefirebase W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
04-28 06:27:38.350 15830-15853/com.example.collegefirebase D/EGL_emulation: eglCreateContext: 0x7fc29c10a6e0: maj 2 min 0 rcv 2
04-28 06:27:38.366 15830-15853/com.example.collegefirebase D/EGL_emulation: eglMakeCurrent: 0x7fc29c10a6e0: ver 2 0 (tinfo 
0x7fc29ca05a80)
04-28 06:27:38.408 15830-15853/com.example.collegefirebase D/EGL_emulation: eglMakeCurrent: 0x7fc29c10a6e0: ver 2 0 (tinfo 0x7fc29ca05a80)

заранее спасибо.

1 Ответ

0 голосов
/ 28 апреля 2020

Сначала вы создаете список неверным образом, и поэтому вы видите множество функций:

вместо этого:

List<College> collegelist = new List<College>();

сделать это:

List<College> collegelist = new ArrayList<College>();

И добавить инициализацию adapter в методе onDataChange():

collegereference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
        {
            collegelist.add(dataSnapshot1.getValue(College.class));
        }

        //create adapter here

        collegeAdapter = new CollegeAdapter(MainActivity.this,collegelist);

        //set the adapter

        recyclerView.setAdapter(collegeAdapter);

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, "unsuccessful", Toast.LENGTH_SHORT).show();
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...