【问题标题】:While click on add Button the list view is adding same data again单击添加按钮时,列表视图再次添加相同的数据
【发布时间】:2020-01-22 10:22:04
【问题描述】:

在我的应用程序中,当列表视图再次在其中添加新数据 item1 和 item 2 时显示 item1 但过去的 item1 数据也存在意味着(item1,item1,item2)这就是我得到的。 在这种情况下,列表视图正在正确获取数据,但是当我添加新数据时,它应该更新列表视图,而不是添加旧数据下方的所有数据

例如:

我在列表视图中添加了 A,它显示 A,现在我在列表视图中添加了 B,而不是它应该显示 A,B,但它显示 A,A,B

    public class Payment extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    Spinner spinner;
    TextView tvPayDate;
    LinearLayout llAccountNo, llChequeNo, llbankName, llDate, llAmount, llAdd;
    Button btnAdd, btnSubmit;
    Calendar calendar;
    SimpleDateFormat dateFormat;
    private String date;
    private RequestQueue mQueue;
    EditText edtAccountNo, edtChequeNo, edtBankName, edtDate, edtAmount, edtOtherText;
    String strAccountNo="", strDate="", strAmount="",  strMonth="", strYear="", strBranch="", strCheckNo="", paymentMode="";
    String token, aksk_no;
    ListView userList;
    UserCustomAdapter userAdapter;
    ArrayList<PayModel> userArray = new ArrayList<>();

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

        tvPayDate = findViewById(R.id.tvPayDate);

        edtAccountNo = findViewById(R.id.edtAccountNo);
        edtChequeNo = findViewById(R.id.edtChequeNo);
        edtBankName = findViewById(R.id.edtBankName);
        edtDate = findViewById(R.id.edtDate);
        edtAmount = findViewById(R.id.edtAmount);
        edtOtherText = findViewById(R.id.edtOtherText);
        llAccountNo = findViewById(R.id.llAccountNo);
        llChequeNo = findViewById(R.id.llChequeNo);
        llbankName = findViewById(R.id.llbankName);
        llDate = findViewById(R.id.llDate);
        llAmount = findViewById(R.id.llAmount);
        llAdd = findViewById(R.id.llAdd);
        btnAdd = findViewById(R.id.btnAdd);
        btnSubmit = findViewById(R.id.btnSubmit);
        mQueue = Volley.newRequestQueue(this);
        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("MM/yyyy");
        String formattedDate = df.format(c);
        String[] separated = formattedDate.split("/");
        strMonth = separated[0];
        strYear = separated[1];
        SharedPreferences prefs = getSharedPreferences("ManaShakti", MODE_PRIVATE);
        token = prefs.getString("token", "");
        aksk_no = prefs.getString("aksk_no", "");
        Intent in = getIntent();
        // tvtotalhrs.setText(in.getStringExtra("hrs"));
        spinner = findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.transaction_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
        calendar = Calendar.getInstance();
        dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        date = dateFormat.format(calendar.getTime());
        tvPayDate.setText(date);
        userAdapter = new UserCustomAdapter(Payment.this, R.layout.row,
                userArray);
        userList =  findViewById(R.id.listView);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (paymentMode.equals("Cash")) {
                    strDate = edtDate.getText().toString();
                    strAmount = edtAmount.getText().toString();
                    int number = Integer.parseInt(edtAmount.getText().toString());
                    if (number > 2000) {
                        edtAmount.setError("Amount should be less than 2000");
                    } else {
                        Add();
                    }
                }
                else if (paymentMode.equals("Cheque")) {
                        strDate = edtDate.getText().toString();
                        strAmount = edtAmount.getText().toString();
                        strCheckNo = edtAccountNo.getText().toString();
                        strBranch = edtBankName.getText().toString();
                    Add();
                }
                else if (paymentMode.equals("UPI Transaction")) {
                        strDate = edtDate.getText().toString();
                        strAmount = edtAmount.getText().toString();
                        strBranch = edtBankName.getText().toString();
                    Add();
                }
                else if (paymentMode.equals("Demand Draft")) {
                        strDate = edtDate.getText().toString();
                        strAmount = edtAmount.getText().toString();
                        strCheckNo = edtAccountNo.getText().toString();
                        strBranch = edtBankName.getText().toString();
                    Add();
                }
            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitData();
           //     checkInputFields();
            }
        });
    }
    private void Add() {
        String akskno = aksk_no.trim();
        final String token1 = token.trim();
        Map<String, String> params = new HashMap<String, String>();
        params.put("a_k_s_no", akskno.trim());
        params.put("year", strYear);
        params.put("month", strMonth);
        params.put("transaction_type", paymentMode);
        params.put("amount", strAmount);
        params.put("bank_name", strBranch);
        params.put("check_dd_no", strAccountNo);
        params.put("date", tvPayDate.getText().toString());
        params.put("token", token1.trim());
        JSONObject json = new JSONObject(params);
        String url = "";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url
                , json, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject object = new JSONObject(String.valueOf(response));
                    String status = object.getString("status");
                    if (status.equals("200")) {
                        try {
                            JSONArray dataJsonArray = object.optJSONArray("data");
                            for (int i = 0; i < dataJsonArray.length(); i++) {
                                PayModel playerModel = new PayModel();
                                JSONObject dataa = dataJsonArray.getJSONObject(i);
                                playerModel.setPaymentMode(dataa.getString("transaction_type"));
                                playerModel.setAmount( dataa.getString("amount"));
                                playerModel.setDate( dataa.getString("date"));
                                playerModel.setId( dataa.getString("transaction_id"));
                                playerModel.setAksk_no( dataa.getString("a_k_s_no"));
                                playerModel.setToken(token1);
                                userArray.add(playerModel);
                            }
                            setupListview();

                        } catch (JSONException ex) {
                            ex.printStackTrace();
                        }
                    } else if (status.equals("201")) {
                        try {
                            JSONArray dataJsonArray = object.optJSONArray("data");
                            for (int i = 0; i < dataJsonArray.length(); i++) {
                                PayModel playerModel = new PayModel();
                                JSONObject dataa = dataJsonArray.getJSONObject(i);
                                playerModel.setPaymentMode(dataa.getString("transaction_type"));
                                playerModel.setAmount( dataa.getString("amount"));
                                playerModel.setDate( dataa.getString("date"));
                                playerModel.setId( dataa.getString("transaction_id"));
                                playerModel.setAksk_no( dataa.getString("a_k_s_no"));
                                playerModel.setToken(token1);
                                userArray.add(playerModel);
                            }
                            setupListview();
                        } catch (JSONException ex) {
                            ex.printStackTrace();
                        }
                    }
                    else {
                        Toast.makeText(Payment.this, "Some Details are Missing", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Log.e("Akash", " " + e);
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Payment.this, "" + error, Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        });
        mQueue.add(jsonObjectRequest);
    }
    private void setupListview() {
        userList.setAdapter(userAdapter);
    }
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if (parent.getItemAtPosition(pos).toString().equals("Cash")) {
            paymentMode = "Cash";
            llAccountNo.setVisibility(View.GONE);
            llChequeNo.setVisibility(View.GONE);
            llbankName.setVisibility(View.GONE);
            llDate.setVisibility(View.VISIBLE);
            llAmount.setVisibility(View.VISIBLE);
        } else if (parent.getItemAtPosition(pos).toString().equals("Cheque")) {
            paymentMode = "Cheque";
            llAccountNo.setVisibility(View.GONE);
            llChequeNo.setVisibility(View.VISIBLE);
            llbankName.setVisibility(View.VISIBLE);
            llDate.setVisibility(View.VISIBLE);
            llAmount.setVisibility(View.VISIBLE);
        } else if (parent.getItemAtPosition(pos).toString().equals("UPI Transaction")) {
            paymentMode = "UPI Transaction";
            llAccountNo.setVisibility(View.GONE);
            llChequeNo.setVisibility(View.GONE);
            llbankName.setVisibility(View.VISIBLE);
            llDate.setVisibility(View.VISIBLE);
            llAmount.setVisibility(View.VISIBLE);
        } else if (parent.getItemAtPosition(pos).toString().equals("Demand Draft")) {
            paymentMode = "Demand Draft";
            llAccountNo.setVisibility(View.GONE);
            llChequeNo.setVisibility(View.VISIBLE);
            llbankName.setVisibility(View.VISIBLE);
            llDate.setVisibility(View.VISIBLE);
            llAmount.setVisibility(View.VISIBLE);
        }
    }
    public void onNothingSelected(AdapterView<?> parent) {
        Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
    }
    public void checkInputFields() {
        if (edtAccountNo.getText() != null)
            strAccountNo = edtAccountNo.getText().toString();
        if (edtChequeNo.getText() != null)
            strCheckNo = edtChequeNo.getText().toString();
        if (edtBankName.getText() != null)
            strBranch = edtBankName.getText().toString();
        if (edtDate.getText() != null)
            strDate = edtDate.getText().toString();
        if (edtAmount.getText() != null)
            strAmount = edtAmount.getText().toString();
        if (!strDate.equalsIgnoreCase("") && !strAmount.equalsIgnoreCase("")
        ) {
            submitData();
        } else {
            Toast.makeText(getApplicationContext(), "All fields are mandatory", Toast.LENGTH_LONG).show();
        }
    }
    private void submitData() {
        Intent intent = new Intent(Payment.this, Upload.class);
        startActivity(intent);
    }
}

这是我的适配器

    public class UserCustomAdapter extends ArrayAdapter<PayModel> {
    Context context;
    int layoutResourceId;
    private RequestQueue mQueue;
    ArrayList<PayModel> data = new ArrayList<PayModel>();


    public UserCustomAdapter(Context context, int layoutResourceId,
                             ArrayList<PayModel> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        UserHolder holder = null;
        mQueue = Volley.newRequestQueue(context);

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new UserHolder();
            holder.textName = (TextView) row.findViewById(R.id.textView1);
            holder.textAddress = (TextView) row.findViewById(R.id.textView2);
            holder.textLocation = (TextView) row.findViewById(R.id.textView3);
            holder.textId = (TextView) row.findViewById(R.id.textView4);
            holder.btnDelete = (Button) row.findViewById(R.id.button2);
            row.setTag(holder);
        } else {
            holder = (UserHolder) row.getTag();
        }
        PayModel user = data.get(position);
        holder.textName.setText(user.getPaymentMode());
        holder.textAddress.setText(user.getAmount());
        holder.textLocation.setText(user.getDate());
        holder.textId.setText(user.getId());
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {

            String date1 = data.get(position).getDate();
            String[] items1 = date1.split("-");
            String date2 = items1[0];
            String month = items1[1];
            String year = items1[2];
            @Override
            public void onClick(View v) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("a_k_s_no", data.get(position).getAksk_no());
                params.put("year", year);
                params.put("month",month);
                params.put("transaction_id", data.get(position).getId());
                params.put("token", data.get(position).getToken());
                JSONObject json = new JSONObject(params);
                String url = "";
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url
                        , json, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            JSONObject object = new JSONObject(String.valueOf(response));
                            String status = object.getString("status");
                            if (status.equals("200")) {
                                Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show();
                                Intent intent=new Intent(context,Payment.class);
                                context.startActivity(intent);
                                ((Activity)context).finish();
                            }
                        } catch (JSONException e) {
                            Log.e("Akash", " " + e);
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });
                mQueue.add(jsonObjectRequest);
            }
        });
        return row;
    }
    static class UserHolder {
        TextView textName;
        TextView textAddress;
        TextView textLocation;
        TextView textId;
        Button btnDelete;
    }
}

【问题讨论】:

  • 使用 list.clear() 在添加新数据之前清除列表。

标签: android android-listview


【解决方案1】:

在从服务器添加数据之前,您需要清除 Arraylist。 这个方法需要清除数据,

    @Override
    public void onResponse(JSONObject response) {
        userArray.clear()// add it first line 
    }

【讨论】:

  • 当我删除一个项目时,你能在适配器中告诉我如何在适配器中设置新的列表视图
  • 删除成功后,需要调用两个方法data.remove(position)和UserCustomerAdapter.this.notifyDataSetChanged();
  • 你应该做的一件事,userArray.clear() 在 if (status.equals("200")) { } 和 else if (status.equals("201")) 中调用它。和。从您之前声明的顶部删除。并在两种情况下都将其添加到第一行。因为如果没有从服务器接收数据(服务器错误情况),您的列表视图不会显示任何数据。
【解决方案2】:

除了之前的答案,当你得到全新的完整列表时,你应该首先通过userArray.clear()清除之前的列表,然后调用userAdapter.notifyDataSetChanged()。 如果您得到的数据应该是在 userArray 中已经存在的额外数据,您应该调用 add()

【讨论】:

  • ` JSONArray dataJsonArray = object.optJSONArray("data"); userArray.clear(); for (int i = 0; i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
相关资源
最近更新 更多