如何在OnItemClickListener中的ListView中传递ID(主键)以从Android应用程序中的SQLite数据库中获取数据?

时间:2015-08-06 18:02:48

标签: android database sqlite

我需要传递ID,它是Android应用程序中SQLite数据库的主键,用于从ListView中获取与数据库相关的数据。收到数据后,会使用intent将其传递给另一个活动。 其他一切都正常工作,但根据点击的列表项,我无法获取数据库中行的ID。

以下是DatabaseHandler.java:

package com.Its_Kush.comety_new;

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

public class DatabaseHandler extends SQLiteOpenHelper {

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

// MainActivity
public static final String dbID = "ID";
public static final String dbNAME = "Name";
public static final String dbEMI = "Emi";
public static final String dbMONTHLY_EXP = "Monthly_Exp";
public static final String dbMEMBERS = "Members";
//
public static final String DATABASE_NAME = "Comety_Database.db";
public static final String TABLE_NAME = "Comety_Database_Table";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;

//

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + dbID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + dbNAME + " TEXT, "
            + dbEMI + " REAL, " + dbMONTHLY_EXP + " REAL, " + dbMEMBERS
            + " INTEGER " + ")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String name, double emi, double monthly_exp,
        int members) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(dbNAME, name);
    content.put(dbEMI, emi);
    content.put(dbMONTHLY_EXP, monthly_exp);
    content.put(dbMEMBERS, members);
    long result = db.insert(TABLE_NAME, null, content);
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor viewOne(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor dataShow = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id, null);
    return dataShow;
}

public Cursor viewAll(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor dataShow = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return dataShow;
}

public boolean updateData(String id, String name, double emi, double monthly_exp, int members){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(dbID, id);
    content.put(dbNAME, name);
    content.put(dbEMI, emi);
    content.put(dbMONTHLY_EXP, monthly_exp);
    content.put(dbMEMBERS, members);
    db.update(TABLE_NAME, content, "id = ?", new String[] { id });
    return true;
}

public int deleteData(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}

public void deleteAll(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " +  TABLE_NAME);
}

public void resetId(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from sqlite_sequence where name = '" + TABLE_NAME + "'");
}

}

以下是包含ListView的类:

    package com.Its_Kush.comety_new;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ShowActivity extends AppCompatActivity {

DatabaseHandler dbComety = new DatabaseHandler(this);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView list1;
Button submit, delete;
EditText id;
String name, str;
double monthly_exp, emi;
short members;

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

    list1 = (ListView) findViewById(R.id.list1);

    show_all();

    list1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            // TODO Auto-generated method stub
            str = (String) ((TextView) v).getText();
            Cursor dataOneView = dbComety.viewOne(str.substring(0, 2));
            if (dataOneView.moveToFirst()) {
                name = dataOneView.getString(1);
                emi = dataOneView.getDouble(2);
                monthly_exp = dataOneView.getDouble(3);
                members = dataOneView.getShort(4);
            }
            // showMessage("Value", "Name: " + name + "\nemi:" + emi
            // + "\nm_exp" + monthly_exp + "\nmembers: " + members);
            // id.setText("");

            Intent submit = new Intent(ShowActivity.this,
                    MainActivity.class);
            submit.putExtra("name", name);
            submit.putExtra("emi", emi);
            submit.putExtra("members", members);
            submit.putExtra("monthly_exp", monthly_exp);

            //
            startActivity(submit);
        }
    });

    list1.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View v,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            str = (String) ((TextView) v).getText();
            showMessage("Delete", "Are you sure?");
            return true;
        }
    });

}

DialogInterface.OnClickListener cancelClickListner = new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub
        finish();
    }
};

public void show_all() {
    Cursor dataView = dbComety.viewAll();
    if (dataView.getCount() == 0) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Error");
        builder.setCancelable(false);
        builder.setMessage("No data found.").setPositiveButton("Back", cancelClickListner).show();
        dbComety.resetId();

    } else {

        String buffer = null;
        if (dataView.moveToFirst()) {
            do {
                buffer = dataView.getString(0) + "\t\t"
                        + dataView.getString(1);
                listItems.add(buffer);
            } while (dataView.moveToNext());
        }
    }
    adapter = new ArrayAdapter<String>(this, R.layout.textview_listitems,
            listItems);

    list1.setAdapter(adapter);
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // Yes button clicked

            int deletedRows = dbComety.deleteData(str.substring(0, 2));
            if (deletedRows > 0) {
                Toast.makeText(ShowActivity.this, R.string.deleted,
                        Toast.LENGTH_SHORT).show();
                adapter.clear();
                show_all();
                adapter.notifyDataSetChanged();
            } else

                Toast.makeText(ShowActivity.this, R.string.not_deleted,
                        Toast.LENGTH_SHORT).show();
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // No button clicked
            break;
        }
    }
};

public void showMessage(String title, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message)
            .setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener);
    builder.show();
}

DialogInterface.OnClickListener deleteAllClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // Yes button clicked

            dbComety.deleteAll();
            adapter.clear();
            show_all();
            adapter.notifyDataSetChanged();
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // No button clicked
            break;
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this
                                                // adds items to the action
                                                // bar if it is present.
    getMenuInflater().inflate(R.menu.show, menu);
    return true;
}



@Override
    public boolean onOptionsItemSelected(MenuItem item) { 
AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.delete_all) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete all");
            builder.setMessage("Are you sure?")
                    .setPositiveButton("Yes", deleteAllClickListener)
                    .setNegativeButton("No", deleteAllClickListener);
            builder.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我目前正在使用String来存储列表项TextView数据,然后使用substring方法获取id。如何直接获取数据库中行的ID?

1 个答案:

答案 0 :(得分:0)

创建行ID列表,并确保id和内容存储在两个列表的相同索引中。

buffer = dataView.getString(1);
idItems.add(dataView.getString(0));
listItems.add(buffer);

并在onitemclicklistener中:

Cursor dataOneView = dbComety.viewOne(idItems.get(position));