简体   繁体   English

RecyclerView 不显示任何项目,除非我按下主页按钮并重新进入活动

[英]RecyclerView not showing any items unless i press homebutton and reenter the activity

The app doesn't show anything in the recycler view the first time I open it, but it shows the items after I press the home button and then press the overview button and open the app from there我第一次打开该应用程序时,它在回收者视图中没有显示任何内容,但是在我按下主页按钮,然后按下概览按钮并从那里打开应用程序后,它会显示项目

here is the code in mainActivity这是 mainActivity 中的代码

public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mlayoutManager;
private ProgressDialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final ArrayList<String> countryNmaeList =new ArrayList<>();

    final ArrayList<countryItem> countryList = new ArrayList<>();
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setMessage("Loading data");



    mRecyclerView = findViewById(R.id.recyclerView);
    mAdapter=new countryAdapter(countryList);

    mlayoutManager=new LinearLayoutManager(this);

    mRecyclerView.setLayoutManager(mlayoutManager);





    dialog.show();
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("https://covid-193.p.rapidapi.com/statistics")
            .get()
            .addHeader("x-rapidapi-host", "covid-193.p.rapidapi.com")
            .addHeader("x-rapidapi-key", "xxxxxxxxxxxxx")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {

        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            dialog.dismiss();
            String response1=response.body().string();
            try {
                //geting Jason object
                JSONObject jsonObject=new JSONObject(response1);
                JSONArray jsonArray = jsonObject.getJSONArray("response");
                for (int i=0;i<jsonArray.length();i++){
                    JSONObject country = jsonArray.getJSONObject(i);
                   JSONObject cases = country.getJSONObject("cases");
                    int activecaseint = cases.getInt("active");
                    int recoveredint =cases.getInt("recovered");
                    JSONObject death= country.getJSONObject("deaths");
                    int dtotal = death.getInt("total");
                    //adding items into country items 
                    countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
                }



            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
    //nottifying the dataset changed 
    mAdapter.notifyDataSetChanged();
    mRecyclerView.setAdapter(mAdapter);


}

}

here is my adapter activity这是我的适配器活动

countryAdapter.java国家/地区适配器

public class countryAdapter extends RecyclerView.Adapter<countryAdapter.countryViewHolder> {
    private ArrayList<countryItem> mCountryList;

    public static class countryViewHolder extends RecyclerView.ViewHolder{
        public TextView mCountryName;
        public TextView mActivePatients;
        public TextView mRecovered;
        public TextView mDeath;

        public countryViewHolder(@NonNull View itemView) {
            super(itemView);
            mCountryName=itemView.findViewById(R.id.CountyNameTv);
            mActivePatients=itemView.findViewById(R.id.activePatientsTv);
            mRecovered=itemView.findViewById(R.id.recoveredTv);
            mDeath=itemView.findViewById(R.id.deathTv);
        }
    }
    public countryAdapter(ArrayList<countryItem> countryList){
        mCountryList = countryList;
    }

    @NonNull
    @Override
    public countryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.itemview,parent,false);
        countryViewHolder cvh =new countryViewHolder(v);
        return cvh;
    }

    @Override
    public void onBindViewHolder(@NonNull countryViewHolder holder, int position) {
        countryItem currentItem=mCountryList.get(position);

        holder.mCountryName.setText(currentItem.getCountryname());
        holder.mActivePatients.setText(currentItem.getActivePatients());
        holder.mRecovered.setText(currentItem.getRecovered());
        holder.mDeath.setText(currentItem.getDeath());
    }

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

    public void swapData(ArrayList<countryItem> list) {
        if (list != null) {
            this.mCountryList.clear();
            this.mCountryList.addAll(list);
            notifyDataSetChanged();
        }
    }
}

i have tried putting notifyDataSetChanged inside the try but that didn't work.我试过将 notifyDataSetChanged 放在 try 中,但这没有用。 i hope you can find a way to fix this.我希望你能找到解决这个问题的方法。

When you have new datalist update after adding it in list as:当您将新的数据列表添加到列表中后进行更新时:

 public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            dialog.dismiss();
            String response1=response.body().string();
            try {
                //geting Jason object
                JSONObject jsonObject=new JSONObject(response1);
                JSONArray jsonArray = jsonObject.getJSONArray("response");
                for (int i=0;i<jsonArray.length();i++){
                    JSONObject country = jsonArray.getJSONObject(i);
                   JSONObject cases = country.getJSONObject("cases");
                    int activecaseint = cases.getInt("active");
                    int recoveredint =cases.getInt("recovered");
                    JSONObject death= country.getJSONObject("deaths");
                    int dtotal = death.getInt("total");
                    //adding items into country items 
                    countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
                }

            //adapter.swapData(countryList);
              updateData(countryList);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

you can comment out following line:您可以注释掉以下行:

 mAdapter.notifyDataSetChanged();

Add this function in your adapter class and call it when you need to update list:在您的适配器类中添加此函数并在您需要更新列表时调用它:

public void swapData(ArrayList<countryItem> list) {
    if (list != null) {
        this.arrayList.clear();
        this.arrayList.addAll(list);
        notifyDataSetChanged();
    }
}

In your global object declaration change type of adapter to:在您的全局对象声明中,将适配器类型更改为:

private countryAdapter mAdapter;

add this method in mainActivity and call when you want to update data:在mainActivity中添加这个方法,需要更新数据时调用:

public void updateData(ArrayList<countryItem> countryList) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            mAdapter.swapData(countryList);
        }
    });
}

Instead of calling mAdapter.notifyDataSetChanged() at the end of onCreate() you should call it in onRespone() when the new data got set.而不是在 onCreate() 结束时调用 mAdapter.notifyDataSetChanged() 您应该在设置新数据时在 onRespone() 中调用它。

@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
    dialog.dismiss();
    String response1=response.body().string();
    try {
        //geting Jason object
        JSONObject jsonObject=new JSONObject(response1);
        JSONArray jsonArray = jsonObject.getJSONArray("response");
        for (int i=0;i<jsonArray.length();i++){
            JSONObject country = jsonArray.getJSONObject(i);
           JSONObject cases = country.getJSONObject("cases");
            int activecaseint = cases.getInt("active");
            int recoveredint =cases.getInt("recovered");
            JSONObject death= country.getJSONObject("deaths");
            int dtotal = death.getInt("total");
            //adding items into country items 
            countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
        }
        mAdapter.notifyDataSetChanged();   // ←  notify adapter here!



    } catch (JSONException e) {
        e.printStackTrace();
    }
}   

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

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