如何从android中的数据库中检索特定行?

时间:2014-08-03 13:10:19

标签: android database

我想从数据库中检索特定的行。实际上,我有一个数据库中项目的列表视图,现在当我点击特定项目时,我想打开一个新活动,它显示属于特定项目的所有信息。

DBAdapter.java

package protect.my.password;

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


// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {

    /////////////////////////////////////////////////////////////////////
    //  Constants & Data
    /////////////////////////////////////////////////////////////////////
    // For logging:
    private static final String TAG = "DBAdapter";

    // DB Fields
    public static final String KEY_ROWID = "_id";
    public static final int COL_ROWID = 0;
    /*
     * CHANGE 1:
     */
    // TODO: Setup your fields here:
    public static final String KEY_WEBSITE = "website";
    public static final String KEY_USERNAME = "username";
    public static final String KEY_PASSWORD = "password";

    // TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
    public static final int COL_WEBSITE = 1;
    public static final int COL_USERNAME = 2;
    public static final int COL_PASSWORD = 3;


    public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_WEBSITE, KEY_USERNAME, KEY_PASSWORD};

    // DB info: it's name, and the table we are using (just one).
    public static final String DATABASE_NAME = "MyDb";
    public static final String DATABASE_TABLE = "mainTable";
    // Track DB version if a new version of your app changes the format.
    public static final int DATABASE_VERSION = 1;   

    private static final String DATABASE_CREATE_SQL = 
            "create table " + DATABASE_TABLE 
            + " (" + KEY_ROWID + " integer primary key autoincrement, "

            /*
             * CHANGE 2:
             */
            // TODO: Place your fields here!
            // + KEY_{...} + " {type} not null"
            //  - Key is the column name you created above.
            //  - {type} is one of: text, integer, real, blob
            //      (http://www.sqlite.org/datatype3.html)
            //  - "not null" means it is a required field (must be given a value).
            // NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
            + KEY_WEBSITE + " text not null, "
            + KEY_USERNAME + " text not null, "
            + KEY_PASSWORD + " string not null"

            // Rest  of creation:
            + ");";

    // Context of application who uses us.
    private final Context context;

    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    /////////////////////////////////////////////////////////////////////
    //  Public methods:
    /////////////////////////////////////////////////////////////////////

    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to the database.
    public long insertRow(String website, String username, String password) {
        /*
         * CHANGE 3:
         */     
        // TODO: Update data in the row with new fields.
        // TODO: Also change the function's arguments to be what you need!
        // Create row's data:
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_WEBSITE, website);
        initialValues.put(KEY_USERNAME, username);
        initialValues.put(KEY_PASSWORD, password);

        // Insert it into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));              
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                            where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String webSite, String userName, String passWord) {
        String where = KEY_ROWID + "=" + rowId;

        /*
         * CHANGE 4:
         */
        // TODO: Update data in the row with new fields.
        // TODO: Also change the function's arguments to be what you need!
        // Create row's data:
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_WEBSITE, webSite);
        newValues.put(KEY_USERNAME, userName);
        newValues.put(KEY_PASSWORD, passWord);

        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }



    /////////////////////////////////////////////////////////////////////
    //  Private Helper Classes:
    /////////////////////////////////////////////////////////////////////

    /**
     * Private class which handles database creation and upgrading.
     * Used to handle low-level database access.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);           
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }
}

Listview.java

package protect.my.password;


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Listview extends Activity {
    ListView listview;
        ArrayAdapter<String> adapter;
    DBAdapter myDb;
    String website;
    String password;
    String username;
    String row_id;

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

        listview = (ListView) findViewById(R.id.dblist);
        this.listview.setEmptyView(findViewById(R.id.emptyElement));
        openDB();
        listviewitems();
        myDb.close();
    }



    private void listviewitems() {

        Cursor cursor = myDb.getAllRows();

        // populate the message from the cursor

        // Reset cursor to start, checking to see if there's data:

                // Process the data:

        List<String> values = new ArrayList<String>();
        if(cursor != null && cursor.moveToFirst()){

        do {
            row_id = cursor.getString(DBAdapter.COL_ROWID);
            website = cursor.getString(DBAdapter.COL_WEBSITE);
            username = cursor.getString(DBAdapter.COL_USERNAME);
            password = cursor.getString(DBAdapter.COL_PASSWORD);

//          Here I have to add the following code to use them all.
//          values.add(website + " - " + username + " - " + password);
//      } while(cursor.moveToNext());
            values.add(website);
        } while(cursor.moveToNext());

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, values);
        listview.setAdapter(adapter);

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

                Intent intent = new Intent(ReadActivity.this, ReadData.class);
                intent.putExtra("RowID", row_id);


                startActivity(intent);

            }
        });
         // Close the cursor to avoid a resource leak.
        cursor.close();


        }   

}
//   Capture ListView item click
//          OnItemClickListener viewNoteListener = new OnItemClickListener() {
//              public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//                      long arg3) {
//      
//                  // Open ViewNote activity
//                  Intent intent = new Intent(ReadActivity.this, ReadData.class);
//                          // Pass the ROW_ID to ViewNote activity
//                  intent.putExtra("intVariableName", id);
//                  startActivity(intent);
//              }
//          };



    private void openDB() {
        myDb = new DBAdapter(this);
        myDb.open();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.read, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        else if (id == R.id.add){

            startActivity(new Intent("protect.my.password.WRITEACTIVITY"));
            finish();
            return true;    

        }
        return false;



    }
}

ReadData.java

     package protect.my.password;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.EditText;

public class ReadData extends Activity {

    EditText et, et1, et2;
    long member_id;
    DBAdapter mydb;
    String website2;
    String username2;
    String password2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read_data);
        mydb = new DBAdapter(this);
        mydb.open();

        et = (EditText) findViewById(R.id.editText3);
        et1 = (EditText) findViewById(R.id.editText1);
        et2 = (EditText) findViewById(R.id.editText2);


        Intent intent = getIntent();

        String RowID1 = intent.getExtras().getString("RowID");


        member_id = Long.parseLong(RowID1);

        Cursor cursor = mydb.getRow(member_id);

        displayRecordSet(cursor);



        et.setText(website2);
        et1.setText(username2);
        et2.setText(password2);

    }
    private void displayRecordSet(Cursor cursor) {
        // TODO Auto-generated method stub
        if(cursor != null && cursor.moveToFirst()){

            do {

                website2 = cursor.getString(DBAdapter.COL_WEBSITE);
                username2 = cursor.getString(DBAdapter.COL_USERNAME);
                password2 = cursor.getString(DBAdapter.COL_PASSWORD);

//              Here I have to add the following code to use them all.
//              values.add(website + " - " + username + " - " + password);
//          } while(cursor.moveToNext());

            } while(cursor.moveToNext());
            cursor.close();
    }
    }
}

我尝试了很多东西,但它没有用。现在我已经删除了我为检索特定行而编写的代码,现在任何人都可以帮助我吗?欢迎任何帮助。

1 个答案:

答案 0 :(得分:0)

我没有看到你在任何地方拨打getRow来获取特定行。您只需拨打getAllRows。如果您确实希望获得单行,请尝试调用您拥有的getRow(long rowId)

编辑:

db.open();
                Cursor c = db.getAllLocationDetails(alarmsSpinner.getSelectedItem().toString());
                if (c.moveToFirst()) {
                    do {
                        alarmNumber = c.getString(c.getColumnIndex(DBAdapter.MY_LOCATION_NUMBER));
                    } while (c.moveToNext());
                    rgMessages.check(R.id.rbReceivedMessages);
                    loadMessages(alarmNumber);
                }
                c.close();
                db.close();

这是我使用的东西。打开db.open(),然后从db调用所需的方法,例如db.getRow(theIdOfYourRow)。然后在if中检索你的行,并将其保存在我想要的alarmNumber变量中。