我如何删除ListView的项目?

时间:2015-02-16 15:50:49

标签: android android-listview items

apk是备忘录或类似的东西。首先你可以把标题和说明放在一起,然后按下按钮"保存"注释已保存并保存在数据库中。如果您按下按钮" Notes",您可以查看包含所有笔记保存在数据库中的列表,您可以选择所有笔记。在屏幕顶部,您可以阅读选择了多少笔记。好的,没关系,但我需要在选中时删除备注,然后按顶部菜单中带有bin图标的按钮。

代码:

package com.example.u2tarea3;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class AnotacionesOpenHelperSingleton extends SQLiteOpenHelper {
    private static AnotacionesOpenHelperSingleton instancia = null;
    private Context mCtx;

    public static AnotacionesOpenHelperSingleton getInstance(Context ctx){
        if(instancia == null){
            instancia = new AnotacionesOpenHelperSingleton(ctx);
        }               
        return instancia;
    }

    private AnotacionesOpenHelperSingleton(Context ctx) {
        super(ctx,"anotaciones",null,2);

    }

    @Override
    public void onCreate(SQLiteDatabase bd) {
        StringBuilder sql = new StringBuilder();

        sql.append("create table IF NOT EXISTS anotaciones (");
        sql.append("_id integer primary key autoincrement,");
        sql.append("texto text not null,");
        sql.append("fecha text not null)");
        bd.execSQL(sql.toString());

    }

    @Override
    public void onUpgrade(SQLiteDatabase bd, int oldVersion, int newVersion) {
        //bd.execSQL("drop table anotaciones");
        bd.execSQL("ALTER TABLE anotaciones ADD titulo text");
        bd.execSQL("UPDATE anotaciones SET titulo = 'sin titulo' WHERE titulo is NULL");

        onCreate(bd); 
    }

}

package com.example.u2tarea3;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity {

    EditText editText;
    EditText editTitulo;
    Button btnGuardar;
    Button btnAnotaciones;
    SQLiteDatabase bd;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton.getInstance(this);
        bd = openHelperSingleton.getWritableDatabase();
        editText = (EditText)findViewById(R.id.editText);
        editTitulo = (EditText) findViewById(R.id.editTitulo);
        btnGuardar = (Button) findViewById(R.id.btnGuardar);
        btnGuardar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                ContentValues valores = new ContentValues();

                valores.put("texto", editText.getText().toString());
                valores.put("fecha", sdf.format(c.getTime()));
                valores.put("titulo", editTitulo.getText().toString());
                bd.insert("anotaciones", null, valores);
                editText.setText("");

            }
        });
        btnAnotaciones = (Button) findViewById(R.id.btnAnotaciones);
        btnAnotaciones.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ListAnotaciones.class);
                startActivity(intent);

            }
        });
    }

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

}

package com.example.u2tarea3;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ListAnotaciones extends ListActivity {
    SQLiteDatabase bd;
    Cursor cursor;
    AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton
            .getInstance(this);
    int cont = 0;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bd = openHelperSingleton.getReadableDatabase();
        cursor = bd.rawQuery("SELECT * FROM anotaciones", null);

        try {
            String[] from = { "fecha", "titulo" };
            int[] to = { R.id.anotacionesFecha, R.id.anotacionesTitulo };

            final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                    R.layout.anotacion, cursor, from, to,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

            setListAdapter(adapter);
            getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
            getListView().setMultiChoiceModeListener(
                    new MultiChoiceModeListener() {

                        @Override
                        public boolean onPrepareActionMode(ActionMode arg0,
                                Menu arg1) {
                            // TODO Auto-generated method stub
                            return false;
                        }

                        @Override
                        public void onDestroyActionMode(ActionMode arg0) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public boolean onCreateActionMode(ActionMode arg0,
                                Menu arg1) {
                            // TODO Auto-generated method stub
                            MenuInflater inflater = arg0.getMenuInflater();
                            inflater.inflate(R.menu.anotaciones, arg1);
                            return true;
                        }

                        @Override
                        public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
                            switch(arg1.getItemId()){
                            case R.id.delete_id:


                            //arg0.finish();

                        default:
                            break;

                            }
                            return true;
                        }

                        @Override
                        public void onItemCheckedStateChanged(ActionMode mode,
                                int position, long id, boolean checked) {

                            int seleccionados = getListView()
                                    .getCheckedItemCount();

                            switch (seleccionados) {
                            case 1:
                                mode.setTitle("1 nota seleccionada");
                                break;
                            default:
                                mode.setTitle("" + seleccionados
                                        + " notas seleccionadas");
                                break;
                            }

                        }
                    });

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

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

1 个答案:

答案 0 :(得分:1)

您需要从数据库和ListView中删除备注,然后调用ListViewAdapter.notifyDataSetChanged()

要从datasource中删除在类中处理datasource的方法:

/**
 * Delete a note given an id.
 * @param id Key used to identify a note to delete.
 */
public void deleteNote(long id) {
    System.out.println("Note deleted with id: " + id);

    database.delete(ListOpenHelper.TABLE_MEMOS,
            ListOpenHelper.ID + " = " + id,
            null);
}

要刷新ListView,您只需通过Views清除并重新添加所有ListViewAdapter

// Refresh adapter view with new data
ListAdapter.clear();
ListAdapter.addAll(dataSource.getAllNotes());
ListAdapter.notifyDataSetChanged();

或者只从ListViewAdapter中移除一个元素,然后调用notifyDataSetChanged();