简体   繁体   中英

Android - Delete an item from Custom Listview and update it when long clicked

In my App, I'm using Custom Listview, where I need to delete an item from Listview as well as corresponding row from CSV file simultaneously when Listview is long clicked.

My CSV file looks like this

2020/11/22,10:30PM,96.3°F,Normal,Body

2020/11/22,10:30PM,98.2°F,Normal,Body

2020/11/22,10:31PM,96.7°F,Normal,Body

2020/11/22,10:40PM,95.0°F,Normal,Body

For instance, if second item from Listview is removed when long clicked, the corresponding data row from CSV file above which is second row on CSV file should also be removed when Listview is long clicked.

Here's my Code:

LogViewActivity.java

public class LogViewActivity extends BaseAppCompatActivity {

    private static final String TAG = "LogViewActivity";

    private File logFile;
    private Toolbar toolbar;
    private ListView lvproducts;
    ArrayList<Product> list;
    ProductAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.log_view_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }



    }

    public void onResume() {
        super.onResume();


        logFile = (File) getIntent().getExtras().get(Constants.EXTRA_LOG_FILE);
        if (logFile != null) {
            toolbar.setTitle(logFile.getName());
            try {
                setLogText(logFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_log_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.action_send_to:
                intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(logFile), "text/plain");
                startActivity(intent);
                break;
            default:
                Log.e(TAG, "Unknown id");
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setLogText(File file) throws FileNotFoundException {

    // Textview visisbility is invisible and used only for setting up String data.

        TextView textView1 = (TextView) findViewById(R.id.tvview1);
        TextView textView2 = (TextView) findViewById(R.id.tvview2);
        TextView textView3 = (TextView) findViewById(R.id.tvview3);
        TextView textView4 = (TextView) findViewById(R.id.tvview4);
        TextView textView5 = (TextView) findViewById(R.id.tvview5);


        lvproducts = (ListView) findViewById(R.id.lvproducts);

        list =new ArrayList<Product>();


        Scanner inputStream;

        inputStream = new Scanner(file);

        while(inputStream.hasNext()){
            String line= inputStream.next();

            if (line.equals("")) { continue; } // <--- notice this line

            String[] values = line.split(",");
            String V = values[0];
            String W= values[1];
            String X= values[2];
            String Y= values[3];
            String Z= values[4];

            // Textview visisbility is invisible and used only for setting up String data.

            textView1.setText(Z);
            textView2.setText(X);
            textView3.setText(Y);
            textView4.setText(V);
            textView5.setText(W);

            Product product1 = new Product(textView1.getText().toString(), textView2.getText().toString(), textView3.getText().toString(), textView4.getText().toString(), textView5.getText().toString());

            list.add(product1);


            adapter = new ProductAdapter(LogViewActivity.this, list);
            lvproducts.setAdapter(adapter);
        }
        inputStream.close();

         lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            int which_item = position;

            new AlertDialog.Builder(LogViewActivity.this)
                    .setTitle(getResources().getString(R.string.delete_log_file_title))
                    .setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
                            + getResources().getString(R.string.file_name))
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    list.remove(which_item);
                                    adapter.notifyDataSetChanged();

                                }
                            })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
            return true;
        }
    });



    }

}

Product.java

public class Product {

    private String mode;
    private String temp;
    private String condition;
    private String dates;
    private String times;

    public Product(String mode, String temp, String condition, String dates, String times) {
        this.mode = mode;
        this.temp = temp;
        this.condition = condition;
        this.dates = dates;
        this.times = times;
    }

    public String getMode() {
        return mode;
    }

    public String getTemp() {
        return temp;
    }

    public String getCondition() {
        return condition;
    }

    public String getDates() {
        return dates;
    }

    public String getTimes() {
        return times;
    }
}

ProductAdapter.java

public class ProductAdapter extends ArrayAdapter<Product> {

    private final Context context;
    private final ArrayList<Product> values;

    public ProductAdapter(@NonNull Context context, ArrayList<Product> list) {
        super(context, R.layout.row_layout, list);
        this.context = context;
        this.values = list;
    }

    @SuppressLint("ResourceAsColor")
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowview = inflater.inflate(R.layout.row_layout, parent, false);

        CardView cdview = (CardView) rowview.findViewById(R.id.cdview);


        TextView tvtemp = (TextView) rowview.findViewById(R.id.tvtemp);
        TextView tvcondition = (TextView) rowview.findViewById(R.id.tvcondition);
        TextView tvdate = (TextView) rowview.findViewById(R.id.tvdate);
        TextView tvtime = (TextView) rowview.findViewById(R.id.tvtime);

        ImageView ivmode = (ImageView) rowview.findViewById(R.id.ivmode);

        tvtemp.setText(values.get(position).getTemp());
        tvcondition.setText(values.get(position).getCondition());
        tvdate.setText(values.get(position).getDates());
        tvtime.setText(values.get(position).getTimes());


        if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (!values.get(position).getTemp().equals("No-Data")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_blue);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.homewhite);
        }

        else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Normal")) && (!values.get(position).getTemp().equals("No-Data")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backgreen);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.headwhite);
        }

        else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Low-Grade-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backyellow);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.headwhite);
        }

        else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("High-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.headwhite);
        }

        else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("HIGH")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.headwhite);
        }

        else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("LOW")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_low);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.headwhite);
        }

        else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.headwhite);
        }

        else if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
        {
            Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
            cdview.setBackground(draw8);
            ivmode.setImageResource(R.drawable.homewhite);
        }

           return rowview;
    }
}

Please help me out. Thank you!

You are only removing item from the loaded data set, therefore only list item is removing. You need to update your csv file on removal of list item

 lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            int which_item = position;

            new AlertDialog.Builder(LogViewActivity.this)
                    .setTitle(getResources().getString(R.string.delete_log_file_title))
                    .setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
                            + getResources().getString(R.string.file_name))
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    list.remove(which_item);
                                    adapter.notifyDataSetChanged();
                                    updateCSVFile();

                                }
                            })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
            return true;
        }
    });

public void updateCSVFile() {
// Write your logic her to update CSV file after item removal.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM