【问题标题】:Passing data in recycler view from API从 API 在回收站视图中传递数据
【发布时间】:2020-09-15 12:26:58
【问题描述】:

我尝试通过观看 Youtube 教程制作一个 covid-19 跟踪应用程序。

我的应用程序显示带有标志的国家/地区列表,当您单击任何国家/地区时,它会打开一个活动并显示该国家/地区的详细信息,即总病例数、死亡人数、康复人数等。Youtube 上的视频使用 ListView,我是使用recyclerView

我成功获取了国家/地区列表并在视图上设置了onClickListener,它打开了第二个活动,详细显示了该案例。但我不知道如何显示数据。

我的适配器类:

class Countries_adapter extends RecyclerView.Adapter<Countries_adapter.MyViewHolder> {


    Context ct;
    List<Countries_data> list;

    public Countries_adapter(Context context,List<Countries_data> country)
    {
        ct=context;
        list=country;
    }


    @Override
    public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(ct).inflate(R.layout.countries_row,parent,false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {

        holder.tvCountryName.setText(list.get(position).getCountry());
        holder.tvtotal.setText(list.get(position).getActive());
        Glide.with(ct).load(list.get(position).getFlag()).into(holder.imageView);

        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ct,CountriesDetails.class);
                i.putExtra("Country",list.get(position).getCountry());
                ct.startActivity(i);
            }
        });


    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvCountryName,tvtotal;
        ImageView imageView;
        LinearLayout linearLayout;
        public MyViewHolder( View itemView) {
            super(itemView);

            tvCountryName = itemView.findViewById(R.id.tvCountryName);
            tvtotal=itemView.findViewById(R.id.tvCountrytotalcaese);
            imageView = itemView.findViewById(R.id.imageFlag);
            linearLayout=itemView.findViewById(R.id.linear_layout);

        }
    }

我的 AffectedCoutries 班级活动如下:

    public class AffectedCountries extends AppCompatActivity {
    
        EditText edtSearch;
       RecyclerView recyclerView;
        SimpleArcLoader simpleArcLoader;
        public static ArrayList countryList = new ArrayList<>();
        Countries_data countryData;
        Countries_adapter  CountriesAdapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_affected_countries);
    
            edtSearch = findViewById(R.id.edtSearch);
            recyclerView=findViewById(R.id.recyclerAffectedCountries);
            simpleArcLoader = findViewById(R.id.loader);
    
          fetchData();
        }
        private void fetchData() {
    
            String url  = "https://corona.lmao.ninja/v2/countries/";
    
            simpleArcLoader.start();
    
            StringRequest request = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
    
                            try {
    
                                JSONArray jsonArray = new JSONArray(response);
    
                                for(int i=0;i<jsonArray.length();i++){
    
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
    
                                    String countryName = jsonObject.getString("country");
                                    String cases = jsonObject.getString("cases");
                                    String todayCases = jsonObject.getString("todayCases");
                                    String deaths = jsonObject.getString("deaths");
                                    String todayDeaths = jsonObject.getString("todayDeaths");
                                    String recovered = jsonObject.getString("recovered");
                                    String active = jsonObject.getString("active");
                                    String critical = jsonObject.getString("critical");
    
                                    JSONObject object = jsonObject.getJSONObject("countryInfo");
                                    String flagUrl = object.getString("flag");
    
                                    countryData = new Countries_data(flagUrl,countryName,cases,todayCases,deaths,todayDeaths,recovered,active,critical);
                                    countryList.add(countryData);
                                }
    
                               CountriesAdapter = new Countries_adapter(AffectedCountries.this,countryList);
                                recyclerView.setLayoutManager(new LinearLayoutManager(AffectedCountries.this));
                                recyclerView.setAdapter(CountriesAdapter);
                                simpleArcLoader.stop();
                                simpleArcLoader.setVisibility(View.GONE);
    
    
                            } catch (JSONException e) {
                                e.printStackTrace();
                                simpleArcLoader.start();
                                simpleArcLoader.setVisibility(View.GONE);
                                Toast.makeText(AffectedCountries.this,"catch response", Toast.LENGTH_SHORT).show();
                            }
    
    
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    simpleArcLoader.stop();
                    simpleArcLoader.setVisibility(View.GONE);
                    Toast.makeText(AffectedCountries.this,"error response", Toast.LENGTH_SHORT).show();
                }
            });
    
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(request);

    }
}

我的国家数据类(模型类)

public class Countries_data {
    public String country;
    public String cases;
    public String todayCases;
    public String deaths;
    public String todayDeaths;
    public String recovered;
    public String active;
    public String critical;
    public String flag;
    
    public Countries_data(String flag, String country, String cases, String 
           todayCases, String deaths, String todayDeaths, String recovered, 
          String active, String critical) {
       

        this.country = country;
        this.cases = cases;
        this.todayCases = todayCases;
        this.deaths = deaths;
        this.todayDeaths = todayDeaths;
        this.recovered = recovered;
        this.active = active;
        this.critical = critical;
        this.flag = flag;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCases() {
        return cases;
    }

    public void setCases(String cases) {
        this.cases = cases;
    }

    public String getTodayCases() {
        return todayCases;
    }

    public void setTodayCases(String todayCases) {
        this.todayCases = todayCases;
    }

    public String getDeaths() {
        return deaths;
    }

    public void setDeaths(String deaths) {
        this.deaths = deaths;
    }

    public String getTodayDeaths() {
        return todayDeaths;
    }

    public void setTodayDeaths(String todayDeaths) {
        this.todayDeaths = todayDeaths;
    }

    public String getRecovered() {
        return recovered;
    }

    public void setRecovered(String recovered) {
        this.recovered = recovered;
    }

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        this.active = active;
    }

    public String getCritical() {
        return critical;
    }

    public void setCritical(String critical) {
        this.critical = critical;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
}

我的 Country_details 课程

public class CountriesDetails extends AppCompatActivity {

    TextView tvCountry, tvCases, tvRecovered,tvdeaths;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_countries_details2);

        tvCountry = findViewById(R.id.tvCountry);
        tvCases = findViewById(R.id.tvCases);
        tvRecovered = findViewById(R.id.tvRecovered);
        tvdeaths=findViewById(R.id.tvTotalDeaths);

        String positionCountry = getIntent().getStringExtra("Country");
        Log.i("country name", positionCountry);

    }
}


    

如何设置tvcases中的数据?

如何显示数据?我是否必须创建一个单独的回收器视图,然后从 API 获取数据,还是可以使用我的主要活动来显示数据?

【问题讨论】:

  • 显示更多来自 logcat 的代码和异常堆栈跟踪
  • 具体来说,“我尝试设置这样的文本,但它在 getCountry() 中出现错误(包含国家名称);”是什么意思什么错误?空指针异常?如果是这样,TextView 是否为空? countryModelsList?
  • @drdaanger tvCountry.setText(AffectedCountries.countryModelsList.get(positionCountry).getCountry());它在 getCountry() 中给出错误,它说无法将方法 getCases() 解析为对象
  • @Abhishek 好的。那么这是构建时异常吗?如果是这种情况,请确保您的 Countries_data 类具有返回 String 或 CharSequence 的公共 getCases 方法。
  • @drdaanger 先生其公众

标签: java android api android-recyclerview


【解决方案1】:

我有一些令人遗憾的信息要告诉您:Google Play 政策限制此类应用在商店中发布...尤其是当您显示死亡人数时。去过那里,完成了,我的应用程序被阻止了......

除此之外:

您有意传递国家/地区名称:

i.putExtra("Country",list.get(position).getCountry());

但尝试阅读 "position" 的详细信息 Activity - 始终是 0(默认)

由于 cmets 而编辑:

通过点击View的位置

holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(ct,CountriesDetails.class);
            i.putExtra("position", position);
            ct.startActivity(i);
        }
    });

CountriesDetailss onCreate 方法中接收此位置并从static countryList 数组中的AffectedCountries 中恢复正确的Countries_data 对象

int position = getIntent().getIntExtra("position", 0);
Countries_data country = AffectedCountries.countryList.get(position);
tvCountry.setText(country.getCountry());

应该可以,但这不是存储数据的最佳方式,实际上它非常弱......下载数据(国家列表)后,您应该以某种方式存储它,例如SQLite/Room lib 或至少 SharedPreferences... 然后在详细活动中您应该恢复 int position 并使用它从数据库或首选项中获取适当的对象,而不是直接从静态数组中获取

在您的Countries_data 中实现Parcelable 接口可能也很有用——这将允许put whole Countries_data object into Intents extras,而不仅仅是具有数组位置的原始int。在这种情况下,详细信息活动甚至不需要访问整个数组或 sql 数据库/首选项,它会直接从Intents extras 获取整个对象

【讨论】:

  • 我不小心这样做了。但是当我尝试设置像 tvCountry.setText(AffectedCountries.countryModelsList.get(positionCountry).getCountry()); 这样的文本时,它在 getCountry() 中给出错误,它说无法将方法 getCases() 解析为对象
  • 再次:显示Activites 和完整异常堆栈跟踪的更多代码(编辑问题,放在那里)
  • 如果适配器代码运行良好,为什么还要发布它? AffectedCountries 是什么? it shows error in getCases(); - 它显示什么错误?把整个stacktrace 返回getCountry() 方法是什么?你试图在另一边读取这个值intgetIntExtra 方法),我敢打赌这是String...
  • AffectedCountries 是我的主要活动类,我使用 `getIntExtra 方法,因为它在适配器类中传递适配器列表位置
  • 对不起,我帮不了你。您没有正确描述问题,没有发布完整或至少相关的代码片段。除此之外:您不是通过position 来接收getIntExtra,而是通过getCountry(),没有人知道这是什么,因为您没有发布Countries_data...
猜你喜欢
  • 2020-06-06
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2021-10-01
  • 2021-03-31
相关资源
最近更新 更多