集成将一个片段之间的数据传递到另一个片段的视图模型时遇到问题,最终将其发送到recycleviewadapter

时间:2019-12-01 16:56:14

标签: android android-fragments architecture parameter-passing viewmodel

应用程序的结构很简单。我有一个片段,它调用对话片段,在接收到数据后,我想通过使用viewmodel(我发现使用最简单)将其发送到另一个片段。在第二个片段中,数据被接收,然后最终传递给recycleviewadapter,以显示数据。我出错了。

false

我正在传递一个自定义书对象,该对象具有getTitle方法,由于空对象错误,我认为没有书被传递。浏览完网络后,我发现一个可能的错误可能是我通过了本书OnCreateView而不是OnActivityCreated,但据我所知,我无法实例化整个recyclerview和layoutmanager等。onActivityCreated。

这是第一个片段

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.newvibe, PID: 10141
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.newvibe.Book.getTitle()' on a null object reference
        at com.example.newvibe.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:45)
        at com.example.newvibe.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:15)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3336)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1187)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:706)
        at android.view.View.measure(View.java:23169)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1638)
        at android.view.View.measure(View.java:23169)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:978)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2718)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1572)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1855)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Process 10141 terminated.

这是接收片段

   import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.Toast;


    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    import androidx.lifecycle.Observer;
    import androidx.lifecycle.ViewModelProviders;


    import java.util.Objects;

    public class FragmentHome extends Fragment implements AddBookDialogue.AddBookDialogueListener, View.OnClickListener {

     private BookViewModel bookPass;
     public Book passedBook;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View w = inflater.inflate(R.layout.fragment_home, container, false);
    Button b = (Button) w.findViewById(R.id.button);
    b.setOnClickListener(this);
    return w;
    }
        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf) {
                    Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
                    Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
                    bookPass.setBook(a);

    }

        @Override
        public void onClick(View w) {
            if (w.getId() == R.id.button) {
                AddBookDialogue addBookDialogue = new AddBookDialogue();
                assert getFragmentManager() != null;
                addBookDialogue.setTargetFragment(FragmentHome.this, 1 );
                addBookDialogue.show(getFragmentManager(), "add book dialogue");

            }
        }

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            bookPass = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(BookViewModel.class);
            bookPass.getBook().observe(getViewLifecycleOwner(), new Observer<Book>() {
                @Override
                public void onChanged(@Nullable Book book) {
                     passedBook = book;
                }
            });
        }
    }

这是recycleviewadapter

import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.Objects;

public class Fragment_Withdrawn extends Fragment {

private RecyclerView mRecyclerview;
private RecyclerView.LayoutManager myLayoutManager;
private RecyclerViewAdapter withDrawnAdapter;
public ArrayList<Book> bookSet;
private BookViewModel bookPass;
public Book passedBook;
    View withdrawnView;
    public Fragment_Withdrawn() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        bookSet = new ArrayList<>();
        bookSet.add(passedBook);
        withdrawnView = inflater.inflate(R.layout.fragment_withdrawn, container, false);
        mRecyclerview = (RecyclerView) withdrawnView.findViewById(R.id.WithdrawnRecycler);
        myLayoutManager= new LinearLayoutManager(getActivity());
        Log.d("debugMode", "mayTest");
        mRecyclerview.setLayoutManager(myLayoutManager);
        withDrawnAdapter = new RecyclerViewAdapter(getContext(  ), bookSet);
        mRecyclerview.setAdapter(withDrawnAdapter);
        return withdrawnView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bookPass = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(BookViewModel.class);
        bookPass.getBook().observe(getViewLifecycleOwner(), new Observer<Book>() {
            @Override
            public void onChanged(@Nullable Book book) {
                passedBook = book;
            }
        });
    }
}

ViewModel

import android.content.Context;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
    public ArrayList<Book> bookSet;
    public Context newContext;


    public static class MyViewHolder extends RecyclerView.ViewHolder{
        public TextView textView;
        public MyViewHolder(View vv) {
            super(vv);
            textView = vv.findViewById(R.id.RecyclerViewTextView);
        }
    }

    public RecyclerViewAdapter(Context newContext , ArrayList<Book> bookSet) {
        this.newContext = newContext; this.bookSet = bookSet;
    }

    @NonNull
    @Override
    public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        view = LayoutInflater.from(newContext).inflate(R.layout.recycler_view_text_view, parent, false);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.MyViewHolder holder, int position) {
        if(!bookSet.isEmpty())
holder.textView.setText(bookSet.get(position).getTitle());
    }

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

最后,以防万一,这里是AddDiaogue,但是它成功地将数据传递到了调用它的片段中

   package com.example.newvibe;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class BookViewModel extends ViewModel {

    private MutableLiveData<Book> book = new MutableLiveData<>();

    public void setBook(Book input){
        book.setValue(input);
    }

    public LiveData<Book> getBook(){
        return book;
    }
}

}

非常感谢您的帮助:)

0 个答案:

没有答案