根据犯罪者选择从服务器获取数据,并在回收者视图中删除旧数据

时间:2019-12-24 08:28:09

标签: java android

我有一个微调器,其中有多个项目。我不希望基于微调器项目选择将请求发送到服务器,并且应该根据选择来获取数据。现在当第二次选择新项目时,它应该获取新数据从服务器中清除数据,然后在“回收者”视图中清除旧数据。

问题:我已经从服务器成功获取数据,但是第二次当我在微调器中选择另一个项目时,它在回收器视图中向我显示的是旧数据。

下面是我的代码。

ProductAdapter.java

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {

private Context context;
private List<ProductsModel> productList;

public ProductAdapter(Context context, List<ProductsModel> productList) {
    this.context = context;
    this.productList = productList;
}

@NonNull
@Override
public ProductAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);

    ViewHolder viewHolder = new ViewHolder(v);

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ProductAdapter.ViewHolder holder, int position) {

    ProductsModel model = productList.get(position);

    holder.marketName.setText(model.getMarketName());

}

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



public class ViewHolder extends RecyclerView.ViewHolder{

    TextView  marketName;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        marketName = itemView.findViewById(R.id.marketName);

     }
   }
}

SelectPack.java

public class SelectPack extends AppCompatActivity {

Spinner marketSpinner;
ProgressBar progress;
RecyclerView products;
List<ProductsModel> productList;

private static final String URL = "https://example.com";

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

    ActionBar ab = getSupportActionBar();
    assert ab!= null;
    ab.setTitle("Select Pack");
    ab.setDisplayHomeAsUpEnabled(true);

    marketSpinner = findViewById(R.id.marketSpinner);
    progress = findViewById(R.id.progress);
    products = findViewById(R.id.products);

    products.setHasFixedSize(true);
    products.setLayoutManager(new LinearLayoutManager(this));

    productList = new ArrayList<>();

    List<String> categories = new ArrayList<String>();
    categories.add("Select market");
    categories.add("Crown");
    categories.add("Long Book A4");
    categories.add("Long Book");

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    marketSpinner.setAdapter(dataAdapter);

    marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            String item = adapterView.getItemAtPosition(i).toString();

            if(item.equals("Select market")){
                progress.setVisibility(View.INVISIBLE);
            }
            else{

                getData(item);
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
}

private void getData(String item){

     progress.setVisibility(View.VISIBLE);

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    RequestBody formBody = new FormBody.Builder()
            .add("name",item)
            .build();

    Request request = new Request.Builder().post(formBody).url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                        if(jsonArray.length() > 0){


                            progress.setVisibility(View.INVISIBLE);

                        }

                        for(int i=0;i<jsonArray.length();i++){

                            progress.setVisibility(View.INVISIBLE);


                            JSONObject object = jsonArray.getJSONObject(i);

                            String str1 = object.getString("market");

                            ProductsModel model = new ProductsModel(str1);

                            productList.add(model);
                        }

             ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
             products.setAdapter(adapter);

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

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    progress.setVisibility(View.INVISIBLE);

                Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

 }

请让我知道在每个新的帖子请求后如何在回收器视图中删除旧数据。任何帮助将不胜感激。

谢谢

0 个答案:

没有答案