Problem when getting an Item from the List view, when the Adapter is filled by a Cursor

1

In my main activity mainActivity I show a listview of the data of my local database in SQlite consulted through a class DataBaseHelper , where the database was created and a class SQLcontrolle where is the cursor method readData which is finally the query itself, the query and the deployment of the same are made perfectly.

What I'm trying to do is that the moment they click on the ITEM, a message will be displayed with the ID or the position or, failing that, the "ID" corresponding to the record in the list, this is what I have until now of code:

  

By clicking on ITEM, it launches me The application has been stopped   of the selected record:

MainActivity.java (Updated 28-02)

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbcon = new SQLController(this);
    dbcon.open();
    lv = (ListView) findViewById(R.id.listView);


    Cursor cursor = dbcon.readData();
    String[] from = new String[] { DatabaseHelper.IDs,    DatabaseHelper.MSG};
    int[] to = new int[] { R.id.ids, R.id.msg};


    SimpleCursorAdapter adapter = new SimpleCursorAdapter(
            MainActivity.this, R.layout.list_item, cursor, from, to);
    Firm = (RadioButton) findViewById(R.id.firma);

    adapter.notifyDataSetChanged();
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            int itemPosition     = position;
            String  itemValue    = (String)   lv.getItemAtPosition(position);
            // Show Message
            Toast.makeText(getApplicationContext(),
                    "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                    .show();
        }
    });

. The SQLController class where the Read Data cursor method is

SQLControler.java

public class SQLController {

private DatabaseHelper DatabaseHelper;
private Context ourcontext;
private SQLiteDatabase database;

public SQLController(Context c) {
    ourcontext = c;
}

public SQLController open() throws SQLException {
    DatabaseHelper = new DatabaseHelper(ourcontext);
    database = DatabaseHelper.getWritableDatabase();
    return this;

}

//Getting Cursor to read data from table
public Cursor readData() {
    String[] allColumns = new String[] { DatabaseHelper.IDs, DatabaseHelper.MSG };
    Cursor c = database.query(DatabaseHelper.TABLE_NAME, allColumns, null,
            null, null, null, DatabaseHelper.IDs+" DESC",null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

And finally DatabaseHelper where I create the database:

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "GCM";
public static final String TABLE_NAME = "newsTable";
public static final String IDs = "_id";
public static final String MSG = "MESSAGE";
public static final String FIRMA = "firma";
public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + IDs + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MSG + " STRING, " + FIRMA + " STRING)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

Any help, suggestion and commentary are grateful in advance, thanks for your attention

    
asked by JESUS ESPINOSA 27.02.2016 в 22:15
source

2 answers

3

I think you are getting the last record because you use "DESC" and then do - > String ids= cursor.getString(0); and this I do not see that change at any time always inquires about 0, and this is the last record by "desc" | cursor.getString ()

  

I do not know how you are managing the Checkbox , in relation to the ListView, but you could try to get the position with something like this:

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView,
                              int myItemInt, long mylng) {

        int sList = lv.getItemAtPosition(myItemInt);

        /*   Aqui puede obtener el item selecionado 
         *  y usarlo para mostrar el mensaje que le
         *  corresponda en lugar de usar el 0 pasandolo
         *  de alguna manera
         *
         *  Nota: Puede que tenga que tener en cuenta la position que le 
         * corresponde a cada item y si esta es la misma para la consulta
         * a la BD porque usted usa desc y no se si lo item se iran 
         * añadiendo de forma dinamica, y tenga que hacer alguna
         * operacion matematica para que la position que obtenga
         * corresponda con el id de la consulta, espero me entienda,
         * aunque es posible que le funcione bien de la forma que esta,
         * pero se lo dejo como observacion
         */ 
      }                 
});

With this method you can check the position of the selected item and use it in some way String ids= cursor.getString(position);

public void onItemClick(AdapterView<?> arg0, View arg1, 
                        int position, long arg3) {      
}

list.setClickable (true);

link

link

As I say, I do not know in what way the listView is implemented, this is just an idea when you see what it shows, but just the same (I do not know if you have it that way) you can put the checkbox inside the holder:

Something like this:

holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
   convertView.setTag(holder);

    holder.name.setOnClickListener( new View.OnClickListener() {

     public void onClick(View v) {  

      CheckBox cb = (CheckBox) v ;  

      Toast.makeText(getApplicationContext(),
                     "Clicked on Checkbox: " + cb.getText() +
                     " is " + cb.isChecked(), 
                     Toast.LENGTH_LONG).show();

     /*
      *Implementar aqui el manejo del cursor
      */
     }  

But it's just an idea I leave you with a full link about the form Previous, you can look at it and determine if it is more comfortable or not, because only you and God knows what you are doing right now and what your idea is.

I hope I help you.

    
answered by 28.02.2016 / 13:34
source
3

Jesus, remember that your Adapter was filled by a Cursor, so your problem is that you are making an incorrect conversion to String:

lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
        ...
        ...
        String  itemValue    = (String)   lv.getItemAtPosition(position);
        ...
        ...
    }
});

It should be:

 Cursor  itemValue    =  (Cursor)  lv.getItemAtPosition(position);
  Toast.makeText(getApplicationContext(),
                    "Position :"+itemPosition+"  ListItem : " +itemValue.getString(0) , Toast.LENGTH_LONG)
                    .show();

With itemValue a Cursor , you can access through the index its fields: itemValue.getString(0), itemValue.getString(1),itemValue.getString(2) , .... etc.

    
answered by 28.02.2016 в 19:39