-1

我是android中数据库的新手。我想知道如何从我的数据库中获取行 ID,例如 NAME。我已经使用以下内容进行了一些研究,现在我坚持显示部分。

       public class DestinateurTable {

                public String TABLE_NAME="destinateur";

                public String ROW_ID="rowid";
                public String NAME="name";
                public String AGENCE="agence";
                public String EMAIL="email";



            }


        public class Destinataire { 


            public String rowid,name,agence,email;


        }


    **My DBHelper.class**


    public class DBHelper {

    private final String DATABASE_PATH = "/data/data/.../databases/";
    private final String DATABASE_NAME = "...sqlite";
    private final static int DATABASE_VERSION = 1;

    private Context context;
    private SQLiteDatabase database = null;
    OpenHelper openHelper=null;
    StringBuilder query =null;
    Cursor cursor=null;

    DestinateurTable destinataireTable = new DestinateurTable();

    public static DBHelper dbHelper = null;

    private DBHelper(Context context) {

    this.context = context;
    openHelper = new OpenHelper(this.context);
    this.database = openHelper.getWritableDatabase();

    try {

        createDataBase();
        openDataBase();

    } catch (IOException e) {

        e.printStackTrace();
    }

    }
    public static DBHelper getInstance(Context context)
    {
    if(dbHelper == null)
        dbHelper = new DBHelper(context);
    return dbHelper;
    }

   public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DATABASE_PATH + DATABASE_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException
    {
    openHelper.getReadableDatabase();
    if(getDBAlreadyCopiedToDeviceOnceFlag(context) == false){
        try {
        copyDataBase();
        setDBAlreadyCopiedToDeviceOnceFlag(context);
        } catch (IOException e) {
        e.printStackTrace();
        throw new Error("Error copying database");
        }
    }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    @SuppressWarnings("unused")
    private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DATABASE_PATH + DATABASE_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DATABASE_NAME);

    // Path to the just created empty db
    String outFileName = DATABASE_PATH + DATABASE_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

    }

    private class OpenHelper extends SQLiteOpenHelper
    {

        @SuppressWarnings("unused")
        SQLiteStatement insertStmt;

        public OpenHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            // TODO Auto-generated method stub
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            // TODO Auto-generated method stub
        }
    }


    public void setDBAlreadyCopiedToDeviceOnceFlag(Context ctx)
    {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("isDBAlreadyCopiedToDeviceOnce", true);
        editor.commit();
    }

    public boolean getDBAlreadyCopiedToDeviceOnceFlag(Context ctx)
    {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        boolean isDBAlreadyCopiedToDeviceOnce = prefs.getBoolean("isDBAlreadyCopiedToDeviceOnce", false);
        return isDBAlreadyCopiedToDeviceOnce; 
    }



    ////////////////////////////
    //// Write your methods here
    ////////////////////////////

    public ArrayList<Destinataire> getDestinataireList()
    {
        ArrayList<Destinataire> items=new ArrayList<Destinataire>();

        try
        {
            query = new StringBuilder();
            query.append("select * from "+destinataireTable.TABLE_NAME);

            cursor=this.database.rawQuery(query.toString(),null);
            if (cursor.moveToFirst())
            {
                do
                {
                    Destinataire d=new Destinataire();

                    d.rowid=cursor.getString(cursor.getColumnIndex(destinataireTable.ROW_ID));
                    d.name=cursor.getString(cursor.getColumnIndex(destinataireTable.NAME));
                    d.agence=cursor.getString(cursor.getColumnIndex(destinataireTable.AGENCE));
                    d.email=cursor.getString(cursor.getColumnIndex(destinataireTable.EMAIL));

                    items.add(d);

                }

                while (cursor.moveToNext());
            }
            if (cursor != null && !cursor.isClosed())
            {
            cursor.close();

            }
        }
        catch(SQLiteException e){

            e.printStackTrace();
            return null;
        }

        return items;
    }

    //--here
    public boolean addDestinataire(Destinataire d){
        this.database.beginTransaction();

        try{

            ContentValues contentValues=new ContentValues();

            contentValues.put(destinataireTable.ROW_ID, d.rowid);
            contentValues.put(destinataireTable.NAME, d.name);
            contentValues.put(destinataireTable.AGENCE, d.agence);
            contentValues.put(destinataireTable.EMAIL, d.email);

            this.database.insert(destinataireTable.TABLE_NAME,null,contentValues);

            this.database.setTransactionSuccessful();

        } catch(Exception e){

            e.printStackTrace();

            return false;

        }   finally{

            this.database.endTransaction();

        }

        return true;
    }


    public boolean deleteDestinataire(String id){

        try {

            String query="delete from " + destinataireTable.TABLE_NAME+" where "+destinataireTable.ROW_ID+"='"+id+"'";
            this.database.execSQL(query);
        }

        catch(SQLiteException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }


}
4

1 回答 1

0

您的整个数据库操作似乎很好。您提到现在要显示数据。最常见的方法是使用连接到Adapter的ListView ,您可以直接将适配器与 Cursor 一起使用,但您已经将它作为 List 获得,因此您可以使用ArrayAdapter

把它当作一个简单的测试,你就开始了解它是如何工作的。创建一个新的 Activity,extends ListActivity然后在其上编写以下代码:

public class MyListActivity extends ListActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         ArrayList<Destinataire> items = getDestinataireList();
         ArrayAdapter<Destinataire> adapter = new ArrayAdapter<Destinataire>(this, android.R.layout.simple_list_item_1 , android.R.id.text1, items)
         setListAdapter(adapter);
    }
}

在 Destinataire 类中也包括这一行:

@Override
public String toString() {
    return name + " " + agence + " " + email;
}

这是一个非常基本的示例,并且没有经过优化(例如,您应该使用后台线程从数据库加载数据),但它应该显示一个列表,其中包含您的数据库中的每个项目显示name agence email.

快乐编码!

编辑:

这一行:

new ArrayAdapter<Destinataire>(this, android.R.layout.simple_list_item_1 , android.R.id.text1, items)

...有一些重要的部分,所以让我解释一下:

  • ArrayAdapter:它的标准行为是为 Array 中的对象调用 toString(),在完成第一部分之后,您可以开始研究 CustomAdapter,以制作更复杂(有趣)的东西。
  • this:这是对 ListActivity 的引用。每个活动都扩展了一个 ContextWrapper,这意味着它们持有对设备资源的引用。对于适配器创建布局非常重要。
  • android.R.layout.simple_list_item_1:这是一个标准的 Android 布局,只有 1 行文本。非常简单,但适合快速测试。它告诉适配器为每个项目使用此布局。
  • android.R.id.text1:布局内文本的ID。它告诉适配器布局中有一个具有该 ID 的 TextView。因此它将从数据对象中获取 toString() 并将其设置为 TextView
  • items:那是你的数据。
于 2013-04-23T08:50:52.727 回答