RecyclerView是片段空

时间:2019-02-02 21:01:15

标签: android android-fragments android-recyclerview nullpointerexception recycler-adapter

我有MainActivity,其中包含viewpager,其中包含2个片段:

MainActivity

ViewPager viewPager =  findViewById(R.id.viewPager);
    MyPagerAdapter adapter = new MyPagerAdapter(this,
            getSupportFragmentManager());
    viewPager.setAdapter(adapter);
    TabLayout tabLayout = findViewById(R.id.TabLayout);
    tabLayout.setupWithViewPager(viewPager);
    Fragment fragmentHour=adapter.getItem(1);
    onChangeDayListener2= (OnChangeDayListener) fragmentHour;

我也有用于从主要活动中发送数据的接口:

    public interface OnChangeDayListener{
    void OnChange(WeatherList list,int pos);
}

但是当我尝试在接口中使用此回调时,我的回收站适配器始终为null:

HourWeatherFragment:

public class HourWeatherFragment extends Fragment implements MainScreen.OnChangeDayListener{
private RecyclerView recyclerView;
private AdapterHour adapter;
private ArrayList<Weather> days;
Context context;
static HttpClient httpClient;
public HourWeatherFragment() {
    // Required empty public constructor
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    days=new ArrayList<>();
    adapter = new AdapterHour(days,getActivity());
    LinearLayoutManager LayoutManager = new LinearLayoutManager(getActivity().getBaseContext(),
            LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(LayoutManager);
    recyclerView.setAdapter(adapter);
    days.add(new Weather());
    recyclerView.getAdapter().notifyDataSetChanged();
    Log.d("recycler","adapter seted!");
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_hour_weather, container, false);
    recyclerView = rootView.findViewById(R.id.hour_list);
    httpClient=new HttpClient();

    MyAsyncTask task=new MyAsyncTask();
     //   task.execute("lviv");
    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context=context;
}

@Override
public void OnChange(WeatherList list,int pos) {
    String date=list.getAverageWeather().get(pos).getDate();
    ArrayList<Weather> weather=list.getByDate(date);
    Log.d("ldata","size of weather for adding="+weather.size());
   // days.add(new Weather());
    if(adapter!=null){
    adapter.notifyDataSetChanged();
        Log.d("tag","first null!");}
    else{
        try{
        recyclerView.getAdapter();}
        catch (NullPointerException ex){
            Log.d("tag","null!");//THERE ALWAYS NULL
        }}

因此,首先创建活动,那么我启动负载数据和数据加载时,我从MainActivity数据发送到HourWeatherFragment throught回调, 但是当我收到片段中的数据时,我的适配器为空,我该如何解决?

3 个答案:

答案 0 :(得分:0)

您可以创建一个静态单例类来保存数据并在片段中检索该数据。

public class DataHolder {

   //create static variables here.

}

在片段中,只需检索数据,然后将其设置为空即可。

替代解决方案

另一种解决方案是使用捆绑包Follow the bundle solution here.

答案 1 :(得分:0)

您必须投射RecyclerView。

在您的片段和onCreateView方法中:

recyclerView = (RecyclerView) rootView.findViewById(R.id.hour_list);

答案 2 :(得分:0)

我知道这是一个古老的问题,但是与公认的答案相反,我认为问题在于OnCreateView函数中不提供片段小部件(例如recyclerView)的句柄。

仅保证 OnViewCreated 函数中存在小部件的句柄(或指针)。

此文档对片段的生命周期有很好的描述: https://guides.codepath.com/android/Creating-and-Using-Fragments

摘录为:

// This event is triggered soon after onCreateView().
// onViewCreated() is only called if the view returned from onCreateView() is non-null.
// Any view setup should occur here.  E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
   super.onViewCreated(view, savedInstanceState);
   ListView lv = (ListView) view.findViewById(R.id.lvSome);
   lv.setAdapter(adapter);
}

希望这会有所帮助。