• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Help with list views, simple cursor adapter and check marks.

Greetings.
I´m new to android development, fairly new, currently I´m trying to make an app that displays a list view using custom rows, in order to do that I´m using a simple cursor adapter and I´m populating it from my DB.
Once a row is created, I declared a long press event that allows me to modify it.
The issue I need help with currently is that, I want to implement a button that allows me to delete selected rows, whether it´s a check mark or not it´s okay.
I´ve checked several tutorials, but some just use the simple list item multiple choice parameters and others directly modify the relative layout, and I haven´t been able to use it.

Can somebody explain me what options are there to do that?

:saddroid:

Here´s the code for the activity:

Code:
import android.app.Activity;
import android.app.ListActivity;
import android.content.ClipData;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.Toast;

//import android.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
import romanempireenterprises.manejador4.Databases.Tasks;
import romanempireenterprises.manejador4.R;

public class Display extends Activity {

    ListView ltvctes;
    Tasks dataSourceAdapter;
    private SimpleCursorAdapter dataAdapter;
    ArrayAdapter<String> valores;

    public void addTasksButton(View v){
        Intent intent =new Intent (getBaseContext(), AddTasks.class);
        startActivity(intent);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        dataSourceAdapter = new Tasks(this);
        dataSourceAdapter.open();
        displayListView();
/*This does not do a shit
        ltvctes = (ListView) findViewById(R.id.listView1);

        valores = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

        dataSourceAdapter = new Tasks(this);

        dataSourceAdapter.open();

        dataSourceAdapter.insertEntry("Tarea de Japonés","5 de Diciembre","2014");

        Cursor c = dataSourceAdapter.getDatabaseInstance().rawQuery("SELECT * FROM TASKS ORDER BY ASUNTO", null);

        // Find ListView to populate
        ListView lvItems = (ListView) findViewById(R.id.listView1);
// Setup cursor adapter using cursor from last step
        Adapter todoAdapter = new Adapter(this, c);
// Attach cursor adapter to the ListView
        lvItems.setAdapter(todoAdapter);
End of useless shit*/
        /*
        if (c.moveToFirst()) {
            do {
                valores.add(c.getString(0) + " " + c.getString(1)+ " " + c.getString(2)+ " " + c.getString(3));//To display password as well use= c.getString(1) + " " + c.getString(2)
            } while (c.moveToNext());
            ltvctes.setAdapter(valores);
        } else {
            Toast.makeText(getApplicationContext(), "No Existen Registros",
                    Toast.LENGTH_SHORT).show();
            this.finish();
        }*/
    }


    @Override
    protected void onResume() {
        super.onResume();
        displayListView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display, menu);

        menu.add(Menu.NONE, Menu.FIRST + 1, Menu.NONE, "Menu Item 1").setIcon(R.drawable.war);

        menu.add(Menu.NONE, Menu.FIRST + 2, Menu.NONE, "Menu Item 2").setIcon(R.drawable.spooder);
        return super.onCreateOptionsMenu(menu);


        }


    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();
        if (id == R.id.itmverctes) {
            Intent intent =new Intent (getBaseContext(), DisplayUsers.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.test) {
            Toast.makeText(this,"Menu Item 1 Clicked", Toast.LENGTH_LONG).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void displayListView() {

        Cursor cursor = dataSourceAdapter.fetchAllEntries();

        // The desired columns to be bound
        String[] columns = new String[] {"_id", "ASUNTO", "FECHA", "INFO"};

        // the XML defined views which the data will be bound to
        int[] to = new int[] {
                R.id.tvID,
                R.id.tvAsunto,
                R.id.tvFecha,
                R.id.tvInfo
        };

        dataAdapter = new SimpleCursorAdapter(
                this,
                R.layout.lvitems,
                cursor,
                Tasks.COLUMNS,
                to,
                0);

        ListView listView = (ListView) findViewById(R.id.list);
        // Assign adapter to ListView
        listView.setAdapter(dataAdapter);
        listView.setTextFilterEnabled(true);
        listView.setLongClickable(true);

        /*New thing*/
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);



        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> listView, View view, int position, long id) {
                // Get the cursor, positioned to the corresponding row in the result set
                Cursor cursor = (Cursor) listView.getItemAtPosition(position);

                // Get the state's capital from this row in the database.
                String _id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
                String asunto = cursor.getString(cursor.getColumnIndexOrThrow("ASUNTO"));
                String fecha = cursor.getString(cursor.getColumnIndexOrThrow("FECHA"));
                String info = cursor.getString(cursor.getColumnIndexOrThrow("INFO"));

                Toast.makeText(getApplicationContext(), "It clicked", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getBaseContext(), UpdateEntry.class);
                intent.putExtra("ID", _id);
                intent.putExtra("Titulo Asunto", asunto);
                intent.putExtra("Fecha", fecha);
                intent.putExtra("Info", info);
                startActivity(intent);
                return true;
            }
        });

        EditText myFilter = (EditText) findViewById(R.id.Filter);
        myFilter.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

                dataAdapter.getFilter().filter(s.toString());

                //Toast.makeText(getApplicationContext(),s, Toast.LENGTH_SHORT).show();



            }
        });

        dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {

                return dataSourceAdapter.fetchAllEntriesByKeyWord(constraint.toString());

            }
        });

    }
}

Here´s the code for the DB
Code:
public class Tasks {

    public static final String DATABASE_NAME = "login.db";
    public static final int DATABASE_VERSION = 1;
    //public static final int NAME_COLUMN = 1;

    public static final String DATABASE_CREATE = "create table " + "TASKS" + "( "
            + "_id" + " integer primary key autoincrement,"
            + "ASUNTO  text, FECHA text, INFO text); ";

    public static final String[] COLUMNS = { "_id", "ASUNTO", "FECHA", "INFO"};

    public SQLiteDatabase db;

    private final Context context;

    private Handler_sqlite dbHelper;

    private static final String TAG = "TaskDbAdapter";

    public Tasks(Context _context) {
        context = _context;
        dbHelper = new Handler_sqlite(context, DATABASE_NAME, null,
                DATABASE_VERSION);
    }

    public Tasks open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public Tasks openReadOnly() throws SQLException {
        db = dbHelper.getReadableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    public SQLiteDatabase getDatabaseInstance() {
        return db;
    }

    public void insertEntry(String asunto, String fecha, String info) {
        ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("ASUNTO", asunto);
        newValues.put("FECHA", fecha);
        newValues.put("INFO", info);

        // Insert the row into your table
        db.insert("TASKS", null, newValues);
        // /Toast.makeText(context, "Reminder Is Successfully Saved",
        // Toast.LENGTH_LONG).show();
    }

    public int deleteEntry(String asunto) {
        // String id=String.valueOf(ID);
        String where = "ASUNTO=?";
        int numberOFEntriesDeleted = db.delete("TASKS", where, new String[] { asunto });
        // Toast.makeText(context,
        // "Number for Entry Deleted Successfully : "+numberOFEntriesDeleted,
        // Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }

    public String getSingleEntry(String asunto) {
        Cursor cursor = db.query("TASKS", null, " ASUNTO=?",
                new String[] { asunto }, null, null, null);
        if (cursor.getCount() < 1) // UserName Not Exist
        {
            cursor.close();
            return null;
        }
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("INFO"));
        cursor.close();
        return password;
    }

    public void updateEntry(String asunto, String fecha, String info) {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("ASUNTO", asunto);
        updatedValues.put("FECHA", fecha);
        updatedValues.put("INFO", info);

        String where = "ASUNTO = ?";
        db.update("TASKS", updatedValues, where, new String[] { asunto });
    }

    public void updateEntryByID(String id, String asunto, String fecha, String info) {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("ASUNTO", asunto);
        updatedValues.put("FECHA", fecha);
        updatedValues.put("INFO", info);

        String where = "_id = ?";
        db.update("TASKS", updatedValues, where, new String[] { id });
    }

    public void clearAll(View v) {
        db.delete(DATABASE_NAME, null, null);
    }

    public Cursor getCursorTasks (){
        return db.query("TASKS", COLUMNS, null, null, null, null, null);
    }

    public Cursor fetchAllEntries() {

        Cursor mCursor = db.query("TASKS", new String[] {"_id",
                        "ASUNTO", "FECHA", "INFO"},
                null, null, null, null, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public Cursor fetchAllEntriesByKeyWord(String inputText) throws SQLException {
        Log.w(TAG, inputText);
        Cursor mCursor = null;
        if (inputText == null  ||  inputText.length () == 0)  {
            mCursor = db.query(
                    "TASKS",
                    new String[] {"_id",
                            "ASUNTO",
                            "FECHA",
                            "INFO"},
                    null, null, null, null, null);

        }
        else {
            mCursor = db.query(
                    true,
                    "TASKS",
                    new String[] {"_id",
                            "ASUNTO",
                            "FECHA",
                            "INFO"},
                    "ASUNTO" + " like '%" + inputText + "%'", null,
                    null, null, null, null);
        }

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

}

The model

Code:
public class Task {
        //private int _id;
        private String asunto = null, fecha=null, info=null;

        /**
         * Constructor de la clase Modelo para las tablas de la BD

        public Task(/*int _id, String asunto, String fecha, String info) {
            /*this._id = _id;
            this.asunto = asunto;
            this.fecha = fecha;
            this.info = info;
        }
        */
        // Getters & setters:
        public String getNombre() {
            return asunto;
        }

        public void setNombre(String asunto) {
            this.asunto = asunto;
        }

        public String getApellido() {
            return fecha;
        }

        public void setApellido(String fecha) {
            this.fecha = fecha;
        }

        public String getTelefono() {
            return info;
        }

        public void setTelefono(String telefono) {
            this.info = info;
        }

        // El campo _id es la clave primaria que no tiene sentido modificar, por lo
        // tanto no le creamos un set a este campo.
        //public int get_id() {
           // return _id;
        //}

    }
 
Back
Top Bottom