从ListView项目获取DB记录ID(带有CursorAdapter和DB Helper的LV)

时间:2017-12-05 19:30:17

标签: android sqlite listview cursor

我正在尝试构建一个简单的应用程序作为学生列表。 MainActivity由 ListView EditText 框和一个'添加'组成。 按钮即可。 我的ListView连接自定义 CursorAdapter ,应用程序使用自定义 SQLiteOpenHelper 数据库。

点击'添加'按钮 - >

将新记录插入到DB - >

DB-Record-ID新添加的ListView项目(通过 bindView

更新新插入的记录

我尝试做的是将ListView项目的 数据库记录ID 传递给新活动,使用Intent.putExtra,但不知道如何在单击的ListView项中获取子文本视图? (在 onItemClick 中,以获取其文本并将其与新Intent一起传递给新活动)

目的要在新活动中使用DB-Record-ID,因为新活动允许用户更新记录中的等级参数(因此,我需要DB-Record- ID以便在更新时在我的数据库上更新它

有人可以提出解决方案吗?这是所需的代码 -

MainActivity:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    /* Our DB model to store student objects */
    private SqlDbHelper mDB;

    /* Custom SQL-Adapter to connect our SQL DB to the ListView */
    private SQLAdapter mAdapter;

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

        /* Init fields & needed views */
        mDB = new SqlDbHelper(getApplicationContext());
        mAdapter = new SQLAdapter(getApplicationContext(), mDB.getAllRows(), false);
        final ListView lvStudents = findViewById(R.id.lv_students);
        final EditText etName = findViewById(R.id.et_name);
        final EditText etGrade = findViewById(R.id.et_grade);

        /* Listen to ADD BUTTON clicks */
        findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertNewRecord(etName.getText().toString(), etGrade.getText().toString());
                etName.setText("");
                etGrade.setText("");
            }
        });

        /* Set adapter to LV, Listen to list item clicks */
        lvStudents.setAdapter(mAdapter);
        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);

                // ????????????
                // listItemIntent.putExtra("_ID",
                //       "Get textview.text containing the param in the CLICKED list item);

                startActivity(listItemIntent);
            }
        });
    }


    /**
     * Creates a list item for a student name + grade
     * @param name
     * @param grade
     * @return the new student id in the DB
     */
    private long insertNewRecord(final String name, final String grade) {
        int gradeInt = -1;
        try {
            gradeInt = Integer.parseInt(grade);
        } catch (NumberFormatException e) {
            Log.w(TAG, "Invalid grade entered: " + grade);
        }

        /* Add the new student to the DB */
        final long id = mDB.insertNewStudent(name, gradeInt);
        mAdapter.changeCursor(mDB.getAllRows());
        return id;
    }
}

不确定是否需要,但以防万一 -

SQLAdapter:

final class SQLAdapter extends CursorAdapter {
    private LayoutInflater mInflater;

    public SQLAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return mInflater.inflate(R.layout.lv_line, viewGroup, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final String name = cursor.getString(cursor.getColumnIndex(SqlDbHelper.KEY_NAME));
        final int grade = cursor.getInt(cursor.getColumnIndex(SqlDbHelper.KEY_GRADE));
        final long id = cursor.getLong(cursor.getColumnIndex(SqlDbHelper.KEY_ID));

        view.findViewById(R.id.ll_line).setBackgroundColor(Color.RED));
        ((TextView)view.findViewById(R.id.tv_name)).setText(name);
        ((TextView)view.findViewById(R.id.tv_grade)).setText(String.valueOf(grade));
        ((TextView)view.findViewById(R.id.tv_id)).setText(String.valueOf(id));
    }
}

SqlDbHelper:

final class SqlDbHelper extends SQLiteOpenHelper {
    private static final String TAG = "SqlDbHelper";

    /* Database version */
    public static final int VERSION = 1;

    /* Relevant string names, keys represent columns */
    public static final String DB_NAME = "StudentsDB";
    public static final String TABLE_NAME = "students";
    public static final String KEY_ID = "_id";
    public static final String KEY_NAME = "Name";
    public static final String KEY_GRADE = "Grade";

    public SqlDbHelper(Context context) {
        super(context, DB_NAME, null, VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        /* Create sql command to create new table */
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE " + TABLE_NAME + " (")
                .append(KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(KEY_NAME + " TEXT,")
                .append(KEY_GRADE + " INT")
                .append(")");

        /* Execute our sql command:
         * CREATE TABLE StudentsDB(_id INTEGER PRIMARY KEY, Name TEXT, Grade INT) */
        Log.d(TAG, "Query to form table: " + sql.toString());
        sqLiteDatabase.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}

    public long insertNewStudent(final String name, final int grade) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_GRADE, grade);
        return getWritableDatabase().insert(TABLE_NAME, null, cv);
    }

    public Cursor getAllRows() {
        return getReadableDatabase().
                rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }
}

1 个答案:

答案 0 :(得分:1)

传递给long l的第四个参数onItemClick,对于CursorAdapter,是id(即根据光标的_id)。

所以只需listItemIntent.putExtra("_ID",l);

e.g。 : -

        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);
                listItemIntent.putExtra("_ID",l); // ID as per _id in the cursor.  
                startActivity(listItemIntent);
            }
        });

评论后编辑: -

  

谢谢,并且为了问题 - 如何获得任何其他   onItemClick中特定列表项的文本视图文本?将   view.findViewById(id_of_the_text_box)会给我正确的文字吗?

是的,如果你想从被点击的项目中访问一个视图,那么使用(假设TextView,其他任何适合视图的内容): -

                view.findViewById(R.id.your_view_id).getText().toString;

所以应用这个你可以: -

        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);
                listItemIntent.putExtra("_ID",l); // ID as per _id in the cursor.  
                listItemIntent.putExtra("_IDFROMVIEW,
                    view.findViewByID(R.id.tv_id).getText().toString();
                startActivity(listItemIntent);
            }
        });

即。它在单击的项目视图列表中找到View(ListView的特定子集/分支(又称adapterView)视图列表)。