简体   繁体   English

无法设置我的 RecyclerView 以显示来自 API 回调的全部数据

[英]Can't setup my RecyclerView to display whole data from API callback

For a longer period of time, I was tried to make this app works, but unfortunately, I've stuck for good.在很长一段时间里,我都试图让这个应用程序正常工作,但不幸的是,我一直坚持下去。 I would like to display hourly forecast in the RecyclerView, but actually I can't, because the program will display last value of the JSON response.我想在 RecyclerView 中显示每小时的预测,但实际上我不能,因为程序将显示 JSON 响应的最后一个值。 I've tried to print everything in console - just for testing purposes, and I've find out that if I use the for loop, then everything works just fine (but unfortunately only in the console) but as long as I don't wanted to hard code the value that I want to receive:我试图在控制台中打印所有内容 - 只是为了测试目的,我发现如果我使用 for 循环,那么一切都很好(但不幸的是只在控制台中)但只要我不这样做想要硬编码我想要接收的值:

for(int i = 0; i<11; i++)

I wanted to do something like this:我想做这样的事情:

for(int i = 0; i<list.size(); i++)

but it'll display again just one value.但它只会再次显示一个值。 How I may finally solve that?我最终如何解决这个问题? Can I have any prompts?我可以有任何提示吗? The response from the API callback is properly for sure. API 回调的响应肯定是正确的。 Here's some code:这是一些代码:

Adapter适配器

List<ForecastModel> forecastData = new ArrayList<>();

@NonNull
@Override
public ForecastViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.forecast_hourly, parent, false);
    return new ForecastViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ForecastViewHolder holder, int position) {


ForecastModel model = forecastData.get(position);
holder.hourlyTemperature.setText(String.valueOf(model.getHourlyForecast().get(position).getTemp()));
    ));
}

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

public void setForecastData(List<ForecastModel> list){
    this.forecastData = list;
    notifyDataSetChanged();
}

 class ForecastViewHolder extends RecyclerView.ViewHolder {
     TextView hourlyTemperature;

     ForecastViewHolder(@NonNull View itemView) {
        super(itemView);
        hourlyTemperature = itemView.findViewById(R.id.hourly_temperature);
    }
}

MainActivity主要活动

    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private ForecastViewModel mViewModel;
    private List<ForecastModel> mForecastList = new ArrayList<>();

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

        mViewModel = new ForecastViewModel(getApplication());

        RecyclerView recyclerView = findViewById(R.id.forecastRecyclerView);
        recyclerView.setLayoutManager( new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setHasFixedSize(true);

        ForecastAdapter adapter = new ForecastAdapter();
        recyclerView.setAdapter(adapter);

        mViewModel.getForecastLiveData().observe(this, new Observer<List<ForecastModel>>() {
            @Override
            public void onChanged(List<ForecastModel> list) {
                if (mForecastList.size() > 0){
                    mForecastList.clear();
                }
                if (list != null){
                    mForecastList.addAll(list);
                    adapter.setForecastData(mForecastList);
                }
            }
        });
    }
}

ViewModel视图模型

    public class ForecastViewModel extends AndroidViewModel {

    private MutableLiveData<List<ForecastModel>> forecastData;
    private static ForecastRepository repository;


    public ForecastViewModel(@NonNull Application application) {
        super(application);
        repository = ForecastRepository.getInstance();
        forecastData = repository.getForecastLiveData();
    }

    public MutableLiveData<List<ForecastModel>> getForecastLiveData(){
        return forecastData;
    }
}

Repository资料库

     private static ForecastRepository instance;
    private ForecastInterface api;

    private ForecastRepository(){
        api = ForecastRetrofitBuilder.getRetrofitBuilder();
    }

    public static ForecastRepository getInstance(){
        if (instance == null){
            instance = new ForecastRepository();
        }
        return instance;
    }

    public MutableLiveData<List<ForecastModel>> getForecastLiveData(){
        MutableLiveData<List<ForecastModel>> liveData = new MutableLiveData<>();

                api.getForecast(35,136,"metric", API_KEY).enqueue(new Callback<ForecastModel>() {
                    @Override
                    public void onResponse(Call<ForecastModel> call, Response<ForecastModel> response) {
                        if (!response.isSuccessful()){
                            Log.w(TAG, "onResponse: !successful "+response.code());
                        }
                        liveData.setValue(Collections.singletonList(response.body()));
                    }

                    @Override
                    public void onFailure(Call<ForecastModel> call, Throwable t) {
                        Log.w(TAG, "onFailure: "+t.getMessage());
                    }
                });
                return liveData;
    }
}

ActivityMain.xml ActivityMain.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".View.MainActivity"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/forecastRecyclerView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"/>

</LinearLayout>

forecast_hourly.xml forecast_hourly.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/hourly_temperature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

There could be many reasons for this, but one obvious reason is:这可能有很多原因,但一个明显的原因是:

liveData.setValue(Collections.singletonList(response.body()));

the live data will always have a single item.实时数据将始终只有一个项目。

And here, you are adding that list which has a single item always, to mForecastList.在这里,您要将始终只有一个项目的列表添加到 mForecastList。

if (mForecastList.size() > 0){
     mForecastList.clear();
}
if (list != null){
     mForecastList.addAll(list);
     adapter.setForecastData(mForecastList);
}

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

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