Using a RecyclerView inside a Fragment instead of an Activity results in E/RecyclerView: No adapter attached; skipping layout error

huangapple go评论89阅读模式
英文:

Using a RecyclerView inside a Fragment instead of an Activity results in E/RecyclerView: No adapter attached; skipping layout error

问题

我最初在CarActivity类中创建并使用了一个RecyclerView。这个工作得很好,从数据库中检索信息并在视图中正确显示出来。然后,我修改了CarActivity类,改为使用一个名为AllCarsFragment的新片段,并将RecyclerView的代码移到了新的AllCarsFragment中。

CarActivity似乎正确地使用了新片段的布局,然而没有数据显示,LogCat显示以下错误:E/RecyclerView: No adapter attached; skipping layout

我尝试过在片段的onCreateViewonViewCreated方法之间移动代码,并以其他方式修改代码,但是我找不到解决方法。

我还在StackOverflow上浏览了类似的问题,但是没有取得任何进展,所以非常感谢任何帮助。

CarActivity.java

public class CarActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_all_cars);
    }
    
}

AllCarsFragment.java

public class AllCarsFragment extends Fragment {
    private static final String LOG_TAG = AllCarsFragment.class.getSimpleName();
    private CarViewModel mCarViewModel;

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_all_cars, container, false);

        // Set up the recycler view to display the users saved cars
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
        final CarListAdapter adapter = new CarListAdapter(view.getContext());
        recyclerView.setAdapter(adapter);

        mCarViewModel = ViewModelProviders.of(this).get(CarViewModel.class);
        mCarViewModel.getAllCars().observe(getViewLifecycleOwner(), new Observer<List<Car>>() {
            @Override
            public void onChanged(@Nullable final List<Car> cars) {
                // Update the cached copy of the cars in the adapter.
                adapter.setCars(cars);
            }
        });

        return view;
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Configure the FAB to redirect the user to add a new car
        FloatingActionButton fab = view.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(LOG_TAG, "Add Car FAB Pressed");
                NavHostFragment.findNavController(AllCarsFragment.this)
                        .navigate(R.id.add_car_dest, null);
            }
        });
    }
}
英文:

I initially created and used a RecyclerView inside my CarActivity class. This worked fine, retrieved the information from the database and displayed it in the view correctly. I then modified the CarActivity class to instead use a new fragment called AllCarsFragment, and moved the RecyclerView code into the new AllCarsFragment.

The CarActivity seems to pick up the layout of the new fragment correctly, however, no data is displayed and LogCat shows the following error: E/RecyclerView: No adapter attached; skipping layout.

I've tried moving the code between the fragments onCreateView and onViewCreated methods and messing with the code in a few other ways, however I can't figure out the fix.

I have also browsed similar questions on StackOverflow, but I'm not getting anywhere, so any help is appreciated.

CarActivity.java

public class CarActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_all_cars);
}
}

AllCarsFragment.java

public class AllCarsFragment extends Fragment {
private static final String LOG_TAG = AllCarsFragment.class.getSimpleName();
private CarViewModel mCarViewModel;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_cars, container, false);
// Set up the recycler view to display the users saved cars
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
final CarListAdapter adapter = new CarListAdapter(view.getContext());
recyclerView.setAdapter(adapter);
mCarViewModel = ViewModelProviders.of(this).get(CarViewModel.class);
mCarViewModel.getAllCars().observe(getViewLifecycleOwner(), new Observer&lt;List&lt;Car&gt;&gt;() {
@Override
public void onChanged(@Nullable final List&lt;Car&gt; cars) {
// Update the cached copy of the cars in the adapter.
adapter.setCars(cars);
}
});
return view;
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Configure the FAB to redirect the user to add a new car
FloatingActionButton fab = view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(LOG_TAG, &quot;Add Car FAB Pressed&quot;);
NavHostFragment.findNavController(AllCarsFragment.this)
.navigate(R.id.add_car_dest, null);
}
});
}
}

Please let me know if you need any further code or info and I'll happily update the question.

答案1

得分: 1

根据您的CarActivity代码,看起来您实际上没有以您打算的方式将AllCarsFragment附加到CarActivity上。setContentView(R.layout.fragment_all_cars)这一行将布局文件设置为CarActivity的内容视图,但这并不会将AllCarsFragment中的代码连接到CarActivity。要实现这一点,您需要在CarActivity的onCreate()中添加一些额外的代码来进行附加。在文档中,查看关于“将片段添加到活动中”的部分。

英文:

From your CarActivity code, it looks as though you're not actually attaching your AllCarsFragment to your CarActivity in the way that you're intending. The line setContentView(R.layout.fragment_all_cars) sets the layout file as the content view of the CarActivity, but this doesn't hook up your code in AllCarsFragment to the CarActivity. To do that, you need some extra code in CarActivity's onCreate() which does the attaching. In the docs, check out the section on "Adding a fragment to an activity".

huangapple
  • 本文由 发表于 2020年10月25日 23:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64525195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定