简体   繁体   English

如何为 recycleview 生成适配器 class 以在片段 class 中使用它?

[英]How to generate an adapter class for recycleview to use it in fragment class?

I am trying to construct an app where I have fragments.我正在尝试构建一个有片段的应用程序。 Inside these fragments, I am using a RecyclerView.在这些片段中,我使用了 RecyclerView。 Also, there is a CardView widget for a Customer entity class under my layouts directory, called card_view_customer.xml .此外,我的布局目录下还有一个Customer实体 class 的 CardView 小部件,名为card_view_customer.xml But, when I create an instance for my current adapter under the CustomerFragment.java class, app is crushing due to some reason I don't know.但是,当我在CustomerFragment.java class 下为我当前的适配器创建一个实例时,由于某种我不知道的原因,应用程序正在崩溃。 I believe the problem is that my adapter is implemented wrongly, but I don't know how to fix it.我认为问题是我的适配器实现错误,但我不知道如何修复它。 These are the codes currently;这些是当前的代码;

onCreateView() function under CustomerFragment.java onCreateView() function 下CustomerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_customer, container, false);
    // Inflate the layout for this fragment
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    final SalesTrackerAdapter adapter = new SalesTrackerAdapter(getActivity());
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mSalesTrackerViewModel = new ViewModelProvider(getActivity()).get(SalesTrackerViewModel.class);
    mSalesTrackerViewModel.getAllCustomers().observe(getActivity(), new Observer<List<Customer>>() {
        @Override
        public void onChanged(List<Customer> customers) {
            adapter.setCustomers(customers);
        }
    });
    return view;
}

card_view_customer.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#00D8D8">

<androidx.cardview.widget.CardView
    android:id="@+id/card_view_customer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:cardCornerRadius="4dp"
    app:contentPadding="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/customerTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            style="@style/customer_title"
            android:layout_alignParentStart="true" />

    </RelativeLayout>
</androidx.cardview.widget.CardView>

fragment_customer.xml where I use RecyclerView我使用RecyclerViewfragment_customer.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".CustomerFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />
</FrameLayout>

And the problem is most likely in this code where I have tried to implement the adapter, but crashes when I used it under onCreateView() function in CustomerFragment.java问题很可能出现在我尝试实现适配器的这段代码中,但是当我在CustomerFragment.java中的onCreateView() function 下使用它时崩溃

SalesTrackerAdapter销售跟踪适配器

public class SalesTrackerAdapter extends RecyclerView.Adapter<SalesTrackerAdapter.SalesTrackerViewHolder> {

    class SalesTrackerViewHolder extends RecyclerView.ViewHolder{

        private final TextView customerTitle;

        private SalesTrackerViewHolder(View itemView){
            super(itemView);
            customerTitle = itemView.findViewById(R.id.customerTitle);
        }
    }

    private final LayoutInflater myInflater;
    private List<Customer> myCustomers;

    SalesTrackerAdapter(Context context){myInflater = LayoutInflater.from(context);}

    @Override
    public SalesTrackerViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View itemView = myInflater.inflate(R.layout.card_view_customer, parent, false);
        return new SalesTrackerViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(SalesTrackerViewHolder holder, int position){
        if (myCustomers != null) {
            Customer current = myCustomers.get(position);
            holder.customerTitle.setText(current.getName());
        } else {
            holder.customerTitle.setText("No Customers");
        }
    }

    void setCustomers(List<Customer> customers){
        myCustomers = customers;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount(){
        if(myCustomers != null){
            return myCustomers.size();
        }
        return 0;
    }
}

I believe something is wrong in this adapter, becaues whenever it is referred in onCreateView() emulator says that the app "keeps stopping".我相信这个适配器有问题,因为每当它在onCreateView()模拟器中被引用时,就会说应用程序“一直在停止”。 When I commented out those lines, it works fine so far.当我注释掉这些行时,到目前为止它运行良好。 What I want is to fetch customers from the database, which I ve done by implementing repository and viewmodel classes and display them inside the cardviews under the fragment.我想要的是从数据库中获取客户,这是我通过实现存储库和视图模型类来完成的,并将它们显示在片段下的卡片视图中。 These are the codes for my repository and ViewModel:这些是我的存储库和 ViewModel 的代码:

public class SalesTrackerRepository {

    //Dao instances.
    private CustomerDao mCustomerDao;
    //Listing items.
    private LiveData<List<Customer>> mAllCustomers;


    SalesTrackerRepository(Application application){
        SalesTrackerDatabase db = SalesTrackerDatabase.getDatabase(application);
        mCustomerDao = db.customerDao();
        mAllCustomers = mCustomerDao.getCustomers();
    }

    LiveData<List<Customer>> getAllCustomers(){
        return mAllCustomers;
    }

    void insert(Customer customer){
        SalesTrackerDatabase.databaseWriteExecutor.execute(() -> mCustomerDao.insert(customer));
    }

}

ViewModel视图模型

public class SalesTrackerViewModel extends AndroidViewModel {

    private SalesTrackerRepository mRepository;

    private LiveData<List<Customer>> mAllCustomers;

    private SalesTrackerViewModel(Application application){
        super(application);
        mRepository = new SalesTrackerRepository(application);
        mAllCustomers = mRepository.getAllCustomers();
    }

    LiveData<List<Customer>> getAllCustomers(){return mAllCustomers;}

    public void insert(Customer customer){mRepository.insert(customer);}
}

I have just started to android and trying to learn with this project.我刚刚开始 android 并尝试学习这个项目。 Sorry for if there are any meaningless points in the question.对不起,如果问题中有任何毫无意义的观点。 Thanks in advance.提前致谢。

Edit: The problem might be in the ViewModel class as well.编辑:问题也可能出在 ViewModel class 中。 I think crash occurs due to following block:我认为由于以下块而发生崩溃:

        mSalesTrackerViewModel = new ViewModelProvider(getActivity()).get(SalesTrackerViewModel.class);
    mSalesTrackerViewModel.getAllCustomers().observe(getActivity(), new Observer<List<Customer>>() {
        @Override
        public void onChanged(List<Customer> customers) {
            adapter.setCustomers(customers);
        }
    });

Edit 2: Here is my logcat编辑 2:这是我的 logcat

    2020-04-19 23:17:09.786 11114-11114/com.example.salestrackertest3 E/lestrackertest: Unknown bits set in runtime_flags: 0x8000
2020-04-19 23:17:12.011 11114-11114/com.example.salestrackertest3 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.salestrackertest3, PID: 11114
    java.lang.RuntimeException: Cannot create an instance of class com.example.salestrackertest3.SalesTrackerViewModel
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:269)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.example.salestrackertest3.CustomerFragment.onCreateView(CustomerFragment.java:90)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:310)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
        at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2167)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1990)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1945)
        at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1816)
        at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:303)
        at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:238)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:760)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:99)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1892)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:831)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:742)
        at android.view.View.measure(View.java:24530)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3006)
2020-04-19 23:17:12.012 11114-11114/com.example.salestrackertest3 E/AndroidRuntime:     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1833)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2122)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7598)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
        at android.view.Choreographer.doCallbacks(Choreographer.java:790)
        at android.view.Choreographer.doFrame(Choreographer.java:725)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.NoSuchMethodException: com.example.salestrackertest3.SalesTrackerViewModel.<init> [class android.app.Application]
        at java.lang.Class.getConstructor0(Class.java:2332)
        at java.lang.Class.getConstructor(Class.java:1728)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
            ... 64 more

The following part of the crash log indicates that the runtime can't find a constructor for your ViewModel崩溃日志的以下部分表明运行时找不到您的ViewModel的构造函数

Caused by: java.lang.NoSuchMethodException: com.example.salestrackertest3.SalesTrackerViewModel.<init> [class android.app.Application] at java.lang.Class.getConstructor0(Class.java:2332) at java.lang.Class.getConstructor(Class.java:1728) at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267) Caused by: java.lang.NoSuchMethodException: com.example.salestrackertest3.SalesTrackerViewModel.<init> [class android.app.Application] at java.lang.Class.getConstructor0(Class.java:2332) at java.lang.Class. getConstructor(Class.java:1728) 在 androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)

... and as a matter of fact the constructor exists but it is private : ...事实上,构造函数存在,但它是private的:

private SalesTrackerViewModel(Application application){
    super(application);
    mRepository = new SalesTrackerRepository(application);
    mAllCustomers = mRepository.getAllCustomers();
}

So the solution is to make the constructor public所以解决方案是让构造函数public

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM