【问题标题】:Recyclerview not showing any dataRecyclerview没有显示任何数据
【发布时间】:2017-03-23 04:15:38
【问题描述】:

我没有在 recyclerview 中使用改造客户端从服务器获取数据。并且在 "Log.d(TAG,"接收的每小时天气数据数量 "+list.size());" 中不显示任何值

Recyclerview 适配器

public class HourlyAdapter extends RecyclerView.Adapter<HourlyAdapter.HourlyViewHolder> {

    List<HourlyList> hourlist;
    Context context;
    public HourlyAdapter(List<HourlyList> hourlist,Context context){
        this.hourlist = hourlist;
        this.context = context;

    }
    @Override
    public HourlyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hourly_list,parent,false);

        return new HourlyViewHolder(view);
    }


    @Override
    public void onBindViewHolder(HourlyViewHolder holder, int position) {
        Date date = new Date(hourlist.get(position).getDt()*1000L);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String formateDate = sdf.format(date);
        holder.hour.setText(formateDate);


    }

    @Override
    public int getItemCount() {
        Log.d("datasize", String.valueOf(hourlist.size()));
        return  hourlist == null ? 0 : hourlist.size();

    }

    public class HourlyViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.hour)
        TextView hour;
        public HourlyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
}

片段文件

public class HourlyFragment extends Fragment {
   @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    List<HourlyList> list;
    HourlyAdapter adapter;


    public HourlyFragment() {
        // Required empty public constructor
    }


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

         ButterKnife.bind(this,view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager lm = new LinearLayoutManager(getActivity());
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(lm);

        adapter = new HourlyAdapter(list,getActivity().getApplicationContext());
        hourlyWeather();


        return view;
    }
    public void hourlyWeather(){
        ApiInterface apiInterface = ApiClient.getRetrofit().create(ApiInterface.class);
        Call<HourlyWeather> call = apiInterface.getHourlyWeather("London","metric",getResources().getString(R.string.api_key));

        call.enqueue(new Callback<HourlyWeather>() {
            @Override
            public void onResponse(Call<HourlyWeather> call, Response<HourlyWeather> response) {

                    list = response.body().getList();


                Log.d(TAG,"Number of hourly weather data received "+list.size());
                recyclerView.setAdapter(adapter);







            }

            @Override
            public void onFailure(Call<HourlyWeather> call, Throwable t) {
                t.printStackTrace();

            }
        });

    }

}

接口文件

@GET("forecast?")
    Call<HourlyWeather> getHourlyWeather(@Query("q") String city,
                                         @Query("units") String units,
                                         @Query("APPID") String appId);

改造客户端

public class ApiClient {
    public static final String BASE_URL="http://api.openweathermap.org/data/2.5/";
    public static Retrofit retrofit =null;

    public static Retrofit getRetrofit(){
        if (retrofit == null){

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;

    }
}

xml文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.example.prem.weatherapp.fragment.HourlyFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/recyclerview"
        android:scrollbars="none"
        android:clipToPadding="false">

    </android.support.v7.widget.RecyclerView>





</RelativeLayout>

数据xml文件列表

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardBackgroundColor="@android:color/transparent"
    android:elevation="0dp"
    app:cardPreventCornerOverlap="false"
    app:contentPadding="0dp">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:id="@+id/date"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/hour"
            android:layout_below="@id/date"/>
    </RelativeLayout>

</android.support.v7.widget.CardView>

【问题讨论】:

  • 您检查堆栈跟踪是否有错误?
  • 您能分享一下您的回复结构吗?
  • list = response.body().getList(); -> 您正在更新对 HourlyFragment 中列表的引用,而不是在适配器中。
  • E/RecyclerView:未连接适配器;跳过布局

标签: android android-recyclerview retrofit


【解决方案1】:

这个问题是您在填充列表之前设置了适配器。在从列表中获得响应之前创建适配器。您必须记住,当您提出改造请求时,您必须等待响应。否则,您只是向适配器发送一个空列表。

你应该做更多这样的事情:

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

         ButterKnife.bind(this,view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager lm = new LinearLayoutManager(getActivity());
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(lm);
        hourlyWeather();


        return view;
    }

 public void hourlyWeather(){
        ApiInterface apiInterface = ApiClient.getRetrofit().create(ApiInterface.class);
        Call<HourlyWeather> call = apiInterface.getHourlyWeather("London","metric",getResources().getString(R.string.api_key));

        call.enqueue(new Callback<HourlyWeather>() {
            @Override
            public void onResponse(Call<HourlyWeather> call, Response<HourlyWeather> response) {

                    list = response.body().getList();

                adapter = new HourlyAdapter(list,getActivity().getApplicationContext());

                Log.d(TAG,"Number of hourly weather data received "+list.size());
                recyclerView.setAdapter(adapter);







            }

【讨论】:

  • 你应该检查你的list。我猜你得到的响应不是你所期望的,或者你的 getList() 方法没有返回你的列表。
【解决方案2】:

我建议使用 Android 的 LoaderManagerAsyncTaskLoader 处理 Retrofit 网络调用,而不是从 onCreateView 调用它。 随意尝试这种方法:

1) 更改HourlyFragment

import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;

public class HourlyFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<HourlyList>> {
    final List<HourlyList> list = new ArrayList<>();
    HourlyAdapter adapter;
    .....

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ......

        adapter = new HourlyAdapter(this.list, getActivity().getApplicationContext());
        recyclerView.setAdapter(adapter);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Loader<List<HourlyList>> onCreateLoader(int arg0, Bundle arg1) {
        return new HourlyWeatherLoader(this.getActivity());
    }

    @Override
    public void onLoadFinished(Loader<List<HourlyList>> arg0, List<HourlyList> datas) {      
        this.list.clear();
        this.list.addAll(datas);

        // this shall update recyclerview to show newly added data
        this.adapter.notifyDataSetChanged();
    }

    @Override
    public void onLoaderReset(Loader<List<HourlyList>> arg0) {
    }

2) 添加新的HourlyWeatherLoader 类来处理改造网络调用

public class HourlyWeatherLoader extends AsyncTaskLoader<List<HourlyList>> {
    private List<HourlyList> list;

    public HourlyWeatherLoader(Context context) {
        super(context);
    }

    @Override
    public List<HourlyList> loadInBackground() {

        ApiInterface apiInterface = ApiClient.getRetrofit().create(ApiInterface.class);
        Call<HourlyWeather> call = apiInterface.getHourlyWeather("London","metric",getResources().getString(R.string.api_key));

        try {
            HourlyWeather hourlyWeather = call.execute().body();
            this.list = hourlyWeather.getList();
        } catch (IOException e) {
            // handle exception catched
            .....
        }

        return this.list;
    }

    @Override
    public void onCanceled(List<HourlyList> list) {
        super.onCanceled(list);
    }

    @Override
    protected void onStopLoading() {
        cancelLoad();
    }

    @Override
    protected void onStartLoading() {
        if (this.list != null) {
            deliverResult(this.list);
        }

        if (takeContentChanged() || this.list == null) {
            forceLoad();
        }
    }

    @Override
    protected void onReset() {
        super.onReset();
        onStopLoading();
        this.list = null;
    }
}

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    试试这个,创建回调接口

    public interface callbackInterface {
          public void onSuccess(yourList);
    }
    

    然后

    hourlyWeather(new callbackInterface() {
            @Override
            public void onSuccess(yourList) {
                   //Set your adapter here.
           }
    }
    

    在每小时天气方法中

    hourlyWeather(callbackInterface ci) {
        //Your retrofit Code goes here
        ci.onSuccess(yourList);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      相关资源
      最近更新 更多