Я слежу за видео на YouTube, чтобы создать проект Firebase для отображения содержимого FireBase в представлении переработчика. Но я застрял, потому что приложение аварийно завершает работу, показывая ошибку, поскольку макет ограничения не может быть приведен к представлению переработчика. Я делюсь всеми кодами, которые я использовал в этом проекте (в частности, связанные с этой ошибкой), пожалуйста, помогите мне с этим проектом
xml код: frag_home. xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="409dp"
android:layout_height="729dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_menu"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
java код (MainHome. java)
package com.example.authentication;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.authentication.Model.Products;
import com.example.authentication.ViewHolder.ProductViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
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 com.squareup.picasso.Picasso;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainHome extends AppCompatActivity {
CircleImageView ProfileImage;
TextView UserName;
FirebaseUser user;
DatabaseReference userName;
String username;
String uid;
private DatabaseReference mDatabase;
private DatabaseReference booksRef;
private AppBarConfiguration mAppBarConfiguration;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_home);
booksRef = FirebaseDatabase.getInstance().getReference().child("Books");
mDatabase = FirebaseDatabase.getInstance().getReference();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
final DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
//For Product Display
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
//For Profile display
ProfileImage = headerView.findViewById(R.id.settings_profile_image);
UserName = headerView.findViewById(R.id.userName);
user = FirebaseAuth.getInstance().getCurrentUser();
uid = user.getUid();
userName = FirebaseDatabase.getInstance().getReference().child("users").child(uid); //Username storage refernce
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl()).into(ProfileImage);
}
userName.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
username = dataSnapshot.child("username").getValue().toString();
UserName.setText(username);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
int id = destination.getId();
switch (destination.getId()) {
case R.id.nav_home:
Toast.makeText(MainHome.this, "Buy Book Fragmet", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_gallery:
finish();
Toast.makeText(MainHome.this, "Sell Book Fragmet", Toast.LENGTH_SHORT).show();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
Intent sellIntent = new Intent(MainHome.this, Add_Product.class);
startActivity(sellIntent);
break;
case R.id.nav_slideshow:
//finish();
Toast.makeText(MainHome.this, "Cart fragment", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_tools:
Toast.makeText(MainHome.this, "Order fragment", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_send:
finish();
Toast.makeText(MainHome.this, "Setting Fragment", Toast.LENGTH_SHORT).show();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
Intent settingIntent = new Intent(MainHome.this, SettingActivity.class);
startActivity(settingIntent);
break;
case R.id.nav_share:
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
finish();
Intent logoutIntent = new Intent(MainHome.this, LoginActivity.class);
startActivity(logoutIntent);
FirebaseAuth.getInstance().signOut();
break;
default:
break;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_home, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options = new FirebaseRecyclerOptions.Builder<Products>().setQuery(booksRef,Products.class).build();
FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull Products model) {
holder.product_name.setText(model.getBname());
holder.product_description.setText(model.getDescription());
holder.product_price.setText("Price:" + model.getPrice() + "Rs");
holder.posted_email.setText(model.getUser_email());
holder.posted_date.setText(model.getDate());
Picasso.get().load(model.getImage()).into(holder.product_image);
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_listner,parent,false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
}
Элементы, которые я хочу отобразить в представлении переработчика
file name : item_listner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="348dp"
android:layout_marginTop="20dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
app:cardElevation="15dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="333dp">
<TextView
android:id="@+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Product Name"
android:textAlignment="center"
android:textColor="@color/colorPrimary"
android:textSize="20dp"
android:textStyle="bold" />
<ImageView
android:id="@+id/product_image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@+id/product_name"
android:layout_marginTop="2dp"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/product_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/product_image"
android:text="Product Price"
android:textAlignment="center"
android:textColor="@color/colorPrimaryDark"
android:textSize="18dp" />
<TextView
android:id="@+id/product_description"
android:layout_width="match_parent"
android:layout_height="44dp"
android:layout_below="@+id/product_price"
android:layout_marginTop="2dp"
android:paddingTop="10dp"
android:text="Product Description"
android:textAlignment="center"
android:textColor="@color/colorPrimaryDark"
android:textSize="16dp" />
<TableRow
android:id="@+id/table"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="@id/product_description">
<TextView
android:id="@+id/textView21"
android:layout_width="68dp"
android:layout_height="match_parent"
android:paddingTop="6dp"
android:text=" Posted:"
android:textColor="@color/colorPrimary" />
<TextView
android:id="@+id/posted_email"
android:layout_width="167dp"
android:layout_height="match_parent"
android:paddingTop="6dp"
android:text=" tejasgudulekar2@gmail.com"
android:textColor="@color/colorPrimaryDark"
android:textSize="12sp" />
<TextView
android:id="@+id/posted_date"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingTop="6dp"
android:text=" 31'Feb 2020"
android:textColor="@color/colorPrimaryDark"
android:textSize="12sp" />
<Button
android:id="@+id/cart_button"
android:layout_width="74dp"
android:layout_height="34dp"
android:text="Added"
android:textColor="@color/colorPrimary" />
</TableRow>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Logcat:
2 14826-14826/com.example.authentication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.authentication, PID: 14826
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.authentication/com.example.authentication.MainHome}: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to androidx.recyclerview.widget.RecyclerView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2747)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
Caused by: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to androidx.recyclerview.widget.RecyclerView
at com.example.authentication.MainHome.onCreate(MainHome.java:92)
at android.app.Activity.performCreate(Activity.java:6845)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2700)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)