我有天气API。我已经为列表项设置了JSON对象,一切正常,并且单击了recycleradapter后就将其删除了。

  public class ForecastAdapters extends RecyclerView.Adapter<ForecastAdapters.ForecastHolder> {

    private Context mContext;
    private List<OpenWeatherMapDaysTo> openWeatherMapDaysTos = new ArrayList<>();
    private OpenWeatherMapDaysTo mOpenWeatherMapDaysTo = new OpenWeatherMapDaysTo();
    private Toast mToast;
    private ForecastAdapters mForecastAdapters;


    public ForecastAdapters(Context context, List<OpenWeatherMapDaysTo> op) {
        mContext = context;
        openWeatherMapDaysTos = op;


    }


    public class ForecastHolder extends RecyclerView.ViewHolder {

        private TextView mTextName, mMornigText, mNightText,mClock;
        private ImageView mImage;

        public ForecastHolder(View view) {
            super(view);
            mTextName = (TextView) view.findViewById(R.id.fr_days_txt);
            mMornigText = (TextView) view.findViewById(R.id.fr_morning);
            mNightText = (TextView) view.findViewById(R.id.fr_night);
            mClock =(TextView)view.findViewById(R.id.fr_clock);
            mImage = (ImageView) view.findViewById(R.id.fr_imageView);


        }

        public void bindData(OpenWeatherMapDaysTo opData) {

            mTextName.setText(VolleyURL.getJustAllDate(opData.getList().get(getAdapterPosition()).getDt_txt()));
            mMornigText.setText(String.format("%d°C", Math.round(opData.getList().get(getAdapterPosition()).getMain().getTemp_max() - 273.15)));
            mNightText.setText(String.format("%d°C", Math.round(opData.getList().get(getAdapterPosition()).getMain().getTemp_min() - 273.15)));
            mClock.setText(String.format(VolleyURL.unixTimeStampToDateTime(opData.getList().get(getAdapterPosition()).getDt())));
            Picasso.with(mContext).load(VolleyURL.getImage(opData.getList().get(getAdapterPosition()).getWeather().get(0).getIcon())).into(mImage);

        }

    }


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

        return new ForecastHolder(view);
    }

    @Override
    public void onBindViewHolder(final ForecastAdapters.ForecastHolder holder, final int position) {
        OpenWeatherMapDaysTo op = openWeatherMapDaysTos.get(position);
        holder.bindData(op);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(mContext, holder.getAdapterPosition()+ " Clicked", Toast.LENGTH_SHORT);
                mToast.show();
          /*      removeAt(holder.getAdapterPosition());*/

            }
        });

    }

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

    }

    public void removeAt(int position) {
        openWeatherMapDaysTos.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, openWeatherMapDaysTos.size());
    }


}


方法是这个

  public void removeAt(int position) {
    openWeatherMapDaysTos.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, openWeatherMapDaysTos.size());
}


我想删除不创建适配器时想要的JSON对象,或者创建适配器,然后删除不需要单击的项目,适配器将被更新并显示出来。那怎么办要么
任何想法。

例如,json包括星期一,星期二,星期三,星期四,星期五等,而且它们是重复的,因为5天预报每3小时包含一次气象数据。
我无法删除三个星期一。

最后,这是我主要活动中的方法,我使用了Volley和gson。

UPDATE-1方法:(我更改了由两个For循环分隔的方法。)

  //get5daysForecast

public void getFiveDays() {
    mProg.setVisibility(View.VISIBLE);
    StringRequest mStringRequest = new StringRequest(Request.Method.POST, VolleyURL.API_GET_FORECAST, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            Gson gson = new Gson();

            Type mType = new TypeToken<OpenWeatherMapDays>() {
            }.getRawType();
            Type mTypeto = new TypeToken<OpenWeatherMapDaysTo>() {
            }.getType();
            openWeatherMapDays = gson.fromJson(response, mType);
            openWeatherMapDaysTo = gson.fromJson(response, mTypeto);

            for (int i = 0; i < openWeatherMapDays.getList().size(); i++) {

                String as = openWeatherMapDays.getList().get(i).getDt_txt();
                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Calendar c = Calendar.getInstance(TimeZone.getTimeZone(as));
                c.add(Calendar.DAY_OF_YEAR, 2);
                String mTomorrow = sdf.format(c.getTime());


                Date dt = null;
                Date dtTomorrow = null;

                try {
                    dt = sdf.parse(as);

                    dtTomorrow = sdf.parse(mTomorrow);


                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

                String finalDate = dateFormat.format(dt);
                String tomorrow = dateFormat.format(dtTomorrow);


                if (finalDate.equals(tomorrow)) {


                    openWeatherMapDays.getList().get(i);
                    mOpenWeatherMapList.add(openWeatherMapDays);
                    mProg.setVisibility(View.INVISIBLE);
                    mCardUpView.setVisibility(View.VISIBLE);
                    mListUPview.setVisibility(View.VISIBLE);
                    mCardForecastAdapters.notifyDataSetChanged();
                }
            }

            for (int j = 0; j < openWeatherMapDaysTo.getList().size(); j++) {

                String as = openWeatherMapDaysTo.getList().get(j).getDt_txt();
                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Calendar c = Calendar.getInstance(TimeZone.getTimeZone(as));
                c.add(Calendar.DAY_OF_YEAR, 2);
                String mTomorrow = sdf.format(c.getTime());


                Date dt = null;
                Date dtTomorrow = null;

                try {
                    dt = sdf.parse(as);

                    dtTomorrow = sdf.parse(mTomorrow);


                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

                String finalDate = dateFormat.format(dt);
                String tomorrow = dateFormat.format(dtTomorrow);

                Log.d(TAG, "FinalDatewitVolley---------;> : " + finalDate.compareTo(VolleyURL.getDateNumber()));
                Log.d(TAG, "VolleyURL:-----------------------> " + VolleyURL.getDateNumber());
                Log.d(TAG, "FinalDate ----------------------->: " + finalDate);


                if ((finalDate.compareTo(VolleyURL.getDateNumber())!=0)) {

                    Log.d(TAG, "===TRUE====: ");
                    openWeatherMapDaysTo.getList().get(j);
                    getmOpenWeatherMapListto.add(openWeatherMapDaysTo);
                    Log.d(TAG, "openWeatherDaysTo SIZE ===>  " + getmOpenWeatherMapListto.size());
                    mForecastAdapters = new ForecastAdapters(getApplicationContext(), getmOpenWeatherMapListto);
                    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
                    mRecyclerView.setLayoutManager(mLayoutManager);
                    mRecyclerView.setAdapter(mForecastAdapters);

                    mForecastAdapters.notifyDataSetChanged();


                }else {
                    Log.d(TAG, "===FALSE====: ");
                }


            }

        }


    }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    })

    {
        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            int mStatusCode = response.statusCode;
            Log.d(TAG, "mStatusCode - FORECAST: " + mStatusCode);

            return super.parseNetworkResponse(response);
        }
    };
    mStringRequest.setRetryPolicy(new

            DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    VolleyController.getmInstance().

            addToRequestQueue(mStringRequest);

}


第二个适配器mCardForecastAdapter正在工作!问题出在mForecastAdapters的“其他”情况下,我已经尝试了if(finalDate.compareTo(VolleyURL.getDateNumber())>0),但是没有用。

我将这些输出。

java - 如何在没有单击的情况下从recyclerview适配器中删除所需的项目?或从 list-LMLPHP

如您所见,当compareTo()返回零时,列表中未包括在内,但是RecyclerView会显示它。

此外:
当我使用这种条件时:

if((finalDate.equals(VolleyURL.getDateNumber()))){
                    openWeatherMapDaysTo.getList().get(i);
                    getmOpenWeatherMapListto.add(openWeatherMapDaysTo);
                    Log.d(TAG, "openWeatherDaysTo SIZE (2) ===>  " + getmOpenWeatherMapListto.size());}


RecyclerAdapter显示前5个项目,所有其他元素均未显示,但我不想显示前5个元素,我想显示前5个元素之后。

编辑1:这是我的模型类和对象

 public class OpenWeatherMapDaysTo {

    private String cod;
    private double message;
    private int cnt;
    private List<Lists2> list;
    private City city;
    private Main main;

    public OpenWeatherMapDaysTo(){

    }

    public OpenWeatherMapDaysTo(String cod, double message, int cnt, List<Lists2> list, City city, Main main) {
        this.cod = cod;
        this.message = message;
        this.cnt = cnt;
        this.list = list;
        this.city = city;
        this.main = main;
    }

    public String getCod() {
        return cod;
    }

    public void setCod(String cod) {
        this.cod = cod;
    }

    public double getMessage() {
        return message;
    }

    public void setMessage(double message) {
        this.message = message;
    }

    public int getCnt() {
        return cnt;
    }

    public void setCnt(int cnt) {
        this.cnt = cnt;
    }

    public List<Lists2> getList() {
        return list;
    }

    public void setList(List<Lists2> list) {
        this.list = list;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }
}


我的lists2类:

  public class Lists2 {

    private int dt;
    private Main main;
    private List<Weather> weather;
    private Clouds clouds;
    private Wind wind;
    private Sys sys;
    private String dt_txt;

    public Lists2(int dt, Main main, List<Weather> weather, Clouds clouds, Wind wind, Sys sys, String dt_txt) {
        this.dt = dt;
        this.main = main;
        this.weather = weather;
        this.clouds = clouds;
        this.wind = wind;
        this.sys = sys;
        this.dt_txt = dt_txt;
    }

    public int getDt() {
        return dt;
    }

    public void setDt(int dt) {
        this.dt = dt;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }

    public Clouds getClouds() {
        return clouds;
    }

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        this.sys = sys;
    }

    public String getDt_txt() {
        return dt_txt;
    }

    public void setDt_txt(String dt_txt) {
        this.dt_txt = dt_txt;
    }
}


和另一个模型类

java - 如何在没有单击的情况下从recyclerview适配器中删除所需的项目?或从 list-LMLPHP

最后:我的问题是

java - 如何在没有单击的情况下从recyclerview适配器中删除所需的项目?或从 list-LMLPHP

最佳答案

编辑1:

据我所知,当您只想显示一个List<Lists2>对象(每个ForecastAdapters项目)时,会将整个预测列表(Lists2)发送到您的RecyclerView

您的for loop正在遍历Lists2对象,据我所知,这是一天中特定时间的预测。这样,您应该创建一个ArrayListArrayList<Lists2> singleDays = new ArrayList<>();)并将日期的每个第一个实例添加到singleDays。在for loop的每次迭代中,检查openWeatherMapDaysTo.getList().get(j)对象是否已存在于singleDays中。如果不存在,则将其添加到singleDays

为了使此代码更简洁,您应该覆盖Lists2类的equals方法。在覆盖的equals方法中,检查日期是否相同,但不是一天中的时间。您可以通过使用仅包含SimpleDateFormat而不包含yyyy-MM-ddHH:mm:ss来实现。

public class Lists2 {
    ...

    @Override
    boolean equals(Object object) {
        if (object == null || !(object instanceof Lists2)) return false;

        Lists2 toCheck = (Lists2) object;

        String thisDateString = getDt_txt();
        String toCheckDateString = toCheck.getDt_txt();

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date thisDate = sdf.parse(thisDateString);
        Date toCheckDate = sdf.parse(toCheckDateString);

        return thisDate.compareTo(toCheckDate) == 0;
    }
}


for loop完成对数据集的迭代之后,可以创建ForecastAdapters并将其分配给RecyclerView

将您的getFiveDays()方法的第二个for loop更改为此

ArrayList<Lists2> singleDays = new ArrayList<>();

for (int j = 0; j < openWeatherMapDaysTo.getList().size(); j++) {
    if (!singleDays.contains(openWeatherMapDaysTo.getList().get(j))) {
        singleDays.add(openWeatherMapDaysTo.getList().get(j));
    }
}

mForecastAdapters = new ForecastAdapters(getApplicationContext(), singleDays);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mForecastAdapters);


另外,创建适配器后无需直接调用mForecastAdapters.notifyDataSetChanged();

您还需要编辑ForecastsAdapter以使用Lists2而不是OpenWeatherMapDaysTo。在绑定数据的地方,无论如何都将获取Lists2的列表以填充视图,因此实际上您实际上仅使用了Lists2对象,但是您正在浏览所有预测的列表以获取它。



原始答案

这都是基于我所做的假设而没有看到称为OpenWeatherMapDaysOpenWeatherMapDaysTo的类

看一下if语句中的代码。

Log.d(TAG, "===TRUE====: ");
openWeatherMapDaysTo.getList().get(j); // line 1
getmOpenWeatherMapListto.add(openWeatherMapDaysTo); // line 2


在第1行上,您正在调用get(j),但未将其分配给任何内容。我假设这是您要在RecyclerView中显示的项目。

在第2行上,您将整个openWeatherMapDaysTo对象(其中包含您不希望使用的天数)添加到getmOpenWeatherMapListto ArrayList(我假设它是ArrayList)。因此,我认为正在发生的事情是,即使您排除了这些先前的项目(基于compareTo检查),它们也将与整个openWeatherMapDaysTo对象一起添加。

我想你想做的是

getmOpenWeatherMapListto.add(openWeatherMapDaysTo.getList().get(j));


根据j计数器添加单日(在您的示例“ 2017年10月24日”中)。

还要在第一个if中检查for loop语句。您调用get(i),但不要将其分配给任何对象。

您可能还想添加break;以在for loop代码块执行后退出TRUE,以防止重新创建ForecastAdapters并再次设置它。

我认为这是您第二个if中的for loop语句的外观(如果我理解您的代码并且您正在尝试完成):

if ((finalDate.compareTo(VolleyURL.getDateNumber())!=0)) {
    Log.d(TAG, "===TRUE====: ");

    getmOpenWeatherMapListto.add(openWeatherMapDaysTo.getList().get(j));

    Log.d(TAG, "openWeatherDaysTo SIZE ===>  " + getmOpenWeatherMapListto.size());

    mForecastAdapters = new ForecastAdapters(getApplicationContext(), getmOpenWeatherMapListto);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mForecastAdapters);
    mForecastAdapters.notifyDataSetChanged();

    // break out of the for loop here otherwise your adapter will be created
    // again and set to your recyclerview
    break;
}

关于java - 如何在没有单击的情况下从recyclerview适配器中删除所需的项目?或从 list ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46906072/

10-09 04:43