我无法检索列表中单击的项目的数据库ID

时间:2016-02-23 19:30:00

标签: java android sqlite

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


    addBtn = (Button)findViewById(R.id.addBtn);
    itemInput = (EditText)findViewById(R.id.itemInput);

    addBtn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            addItem(itemInput.getText().toString());
            itemInput.setText("");
        }
    });

    handler = new MyDbHandler(this,null,null,1);

    mylist = (ListView) findViewById(R.id.listView);
    mylist.setOnItemClickListener(
            new AdapterView.OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {

            Log.d("Clicked item id", " "+position);

        }

    });
    getList();

}

上面是我的主要活动,在环顾四周之后,我找到了一个解决方案,表示position参数代表我在数据库中的项ID,但这对我不起作用。我想获取在列表中单击的项目的数据库ID。

package com.lagfvu.quicklist;

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

import java.util.ArrayList;

/**
 * Created by musaddiq on 2/23/16.
 */
public class MyDbHandler extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 5;
    private static final String DATABASE_NAME = "quicklist.db";
    private static final String ITEMS_TABLE = "list";
    private static final String COLUMN_ID = "_id";
    private static final String COLUMN_NAME = "itemname";


    public MyDbHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        String query = "CREATE TABLE "+ ITEMS_TABLE + "(" + COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME +" TEXT"+");";
        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS "+ ITEMS_TABLE);
        onCreate(db);
    }


    public void addItem(String item)
    {
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_NAME,item);
        SQLiteDatabase db = getWritableDatabase();
        db.insert(ITEMS_TABLE, null, cv);
        db.close();
    }

    public void deleteItem(long id)
    {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM " + ITEMS_TABLE + " WHERE " + COLUMN_ID + "=\"" + id + "\";");
    }

    //print out as string

    public ArrayList<String> DbToList()
    {
        ArrayList<String> itemList = new ArrayList<>();

        SQLiteDatabase db = getWritableDatabase();


        String query = "SELECT "+ COLUMN_NAME +" FROM "+ ITEMS_TABLE + "\n";

        //cursor pointer
        Cursor cursor = db.rawQuery(query,null);

        //move to first row in results
        cursor.moveToFirst();
        while(!cursor.isAfterLast())
        {
            if(cursor.getString(cursor.getColumnIndex("itemname"))!= null)
            {
                itemList.add(cursor.getString(cursor.getColumnIndex("itemname")));
            }
            cursor.moveToNext();
        }

        db.close();
        return itemList;
    }
}

这是我的dbhandler类。

2 个答案:

答案 0 :(得分:1)

我在我的应用程序中使用了类似的东西,我是一个使用复选框的自定义游标适配器,一旦检查它将显示row_id,光标用于调用数据库以获取相关信息,然后依赖于行的id被展示。可能不是最好的方式,但我相信你可以扭转它来满足你的需求,希望它有所帮助

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SimpleCursorAdapter;

public class CustomAdapter extends SimpleCursorAdapter implements CompoundButton.OnCheckedChangeListener {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);
    CheckBox checkBox1 = (CheckBox) view.findViewById(R.id.checkBox1);
    checkBox1.setOnCheckedChangeListener(this);
    int columnIndex = cursor.getColumnIndex("_id");
    int columnvalue = cursor.getInt(columnIndex);
    checkBox1.setTag(columnvalue);

}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = (Integer) buttonView.getTag();
        Toast.makeText(getApplicationContext(), "The id is " + id, Toast.LENGTH_SHORT).show();


}

}

答案 1 :(得分:1)

MyDbHandler类中没有任何方法来获取数据。 从数据库获取数据。 将该代码粘贴到MyDbHandler.java类中。

public Cursor fetchAllData() {
    SQLiteDatabase mDb = getWritableDatabase();
        Cursor mCursor = mDb.query(ITEMS_TABLE, new String[]{COLUMN_ID, COLUMN_NAME},
                null, null, null, null, null);

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

在Cursor的帮助下获取特定的项目_id。

将该代码粘贴到MainActivity.java

MyDbHandler handler = new MyDbHandler(this,"quicklist.db",null,1);

  ListView  mylist = (ListView) findViewById(R.id.listView);
    mylist.setOnItemClickListener(
            new AdapterView.OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
           Cursor cursor=handler.fetchAllData();
          cursor.moveToPosition(position);
           String _id=cursors.getString(cursor.getColumnIndex("_id"));
           Log.d("Clicked item id", " "+_id);

        }
});