如何在没有Clicked的情况下从recyclerview适配器中删除所需的项目?或者来自List

时间:2017-10-24 08:51:42

标签: java android json arraylist

我有天气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),但它没有用。

我接受这些输出。

This

正如您所看到的,当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个元素后显示。

Edit-1:这是我的Model类和对象

 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;
    }
}

my lists2 class:

  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;
    }
}

和另一个Model类

these

最后:我的问题是

phone view

2 个答案:

答案 0 :(得分:0)

编辑1:

据我所知,当您只想展示一个List<Lists2>对象时,我会将整个预测列表ForecastAdapters发送给您Lists2RecyclerView项)。

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

为了使此代码更清晰,您应该覆盖Lists2类的equals方法。在重写的equals方法中,您检查日期是否相同,但不是一天中的时间。您可以使用仅包含SimpleDateFormat且不包含yyyy-MM-dd的{​​{1}}来执行此操作。

HH: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对象,但是您正在查看所有预测的列表得到它。

原始答案

这完全基于我所做的假设而没有看到名为Lists2OpenWeatherMapDays

的类

查看OpenWeatherMapDaysTo声明中的代码。

if

在第1行,您正在调用Log.d(TAG, "===TRUE====: "); openWeatherMapDaysTo.getList().get(j); // line 1 getmOpenWeatherMapListto.add(openWeatherMapDaysTo); // line 2 ,但不会将其分配给任何内容。我假设这是您要在get(j)中显示的项目。

在第2行,您要将整个RecyclerView对象(其中包含您不想要的日期列表)添加到openWeatherMapDaysTo getmOpenWeatherMapListto(我假设它是{{1} }})。所以我认为即使您排除了之前的项目(基于ArrayList检查),它们也会被添加到整个ArrayList对象中。

我认为你想要做的是,

compareTo

根据openWeatherMapDaysTo计数器添加单日(在您的示例&#34; 2017年10月24日和#34;)。

同时检查您的第一个getmOpenWeatherMapListto.add(openWeatherMapDaysTo.getList().get(j)); 中的j语句。您拨打if,但不要将其分配给任何内容。

您可能还希望在for loop代码块执行后添加get(i)退出break;,以防止重新创建for loop并重新设置。< / p>

以下是我认为您的第二个TRUE中的ForecastAdapters语句应该是这样的(如果我了解您的代码和您要完成的代码):

if

答案 1 :(得分:0)

我在Volley Request中编写了这段代码,这个问题就解决了。

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

                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Calendar c = Calendar.getInstance();
                c.add(Calendar.DAY_OF_YEAR, 0);
                String mNowDay = sdf.format(c.getTime());
                Date dtNow = null;

                Calendar cT = Calendar.getInstance();
                cT.add(Calendar.DAY_OF_YEAR, 1);
                String mTomorrow = sdf.format(cT.getTime());

                Date dtTomorrow = null;

                try {
                    dtNow = sdf.parse(mNowDay);
                    dtTomorrow = sdf.parse(mTomorrow);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                String finalDate = dateFormat.format(dtNow);
                String finalTomorrow = dateFormat.format(dtTomorrow);

                Log.d(TAG, "JSON ----------------------->: " + VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()));
                Log.d(TAG, "VolleyURL.getDateNumber----------------------->: " + VolleyURL.getDateNumber());
                Log.d(TAG, "FINALDATE ---------> : " + finalDate);
                Log.d(TAG, "IF IC ---------> : " + VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()));

                if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 12:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");


                    openWeatherMapDaysTo.getList().remove(j);
                    j--;


                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 15:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;

                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 18:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;

                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 21:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;
                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalTomorrow + " 00:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;
                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalTomorrow + " 03:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;
                } else {
                    Log.d(TAG, " \n ===FALSE====: ");
                    getmOpenWeatherMapListto.add(openWeatherMapDaysTo);


                }

我无法将else-if语句转换为switch-case语句。但它现在完全正常工作。如果您有与此问题相关的建议(与声明转换相关),我很乐意听到。

ScreenShot