2015-10-20 28 views
1

ANSWER SQLite的單細胞和顯示:請注意,我使用這兩種建議的組合以產生以下的代碼:抓取在單一的TextView

DBAdapter.java:

String name = ""; 

public String getName(long l) { 
    Cursor result = myDBHelper.getReadableDatabase().query(
      DBAdapter.DATABASE_TABLE_NAME, //Name of your table 
      new String[] { DBAdapter.KEY_NAME }, //List of columns to return, as a String array. Just one in your case. 
      DBAdapter.KEY_ROWID + "=?", //The row selection criteria. Equivalent to saying "Where the key id is equal to..." 
      new String[] { String.valueOf(l) }, //...this value 
      null, //This parameter deals with grouping results. No need here, hence null. 
      null, //Relates to the above. Also null. 
      null //Orders results. There should just be one, so it's null here, but can be useful. 
    ); 

    if (result.moveToFirst()) { 
     name = result.getString(result.getColumnIndex(DBAdapter.KEY_NAME)); 
    } 
    return name; 

CharacterInfo.java(NavigationDrawer親本):

DBAdapter myDb = new DBAdapter(this); 

myDb.open(); 
String name = myDb.getName(1); 
mTitle1 = name; 
myDb.close(); 

雖然這產生了錯誤的環境中,應用程序崩潰由於"No such table"錯誤(code 1)這我還沒有解決。

END ANSWER

首先,我知道有很多這些類型的問題。我已經看了至少一打,似乎無法把頭圍住它,所以我發佈了一個問題,希望有人能幫我一個忙,並在提供方法的同時更詳細地向我解釋。

我想創建一個方法,爲我指定的KEY_ROWID提取KEY_NAME。 (我認爲這可以使用已經在DBAdapter中的getRow()方法來完成)。然後,將其轉換爲一個字符串以顯示它TextView

我需要知道如何在DBAdapter命名getName

底部填寫方法一個完美的答案,讓我寫了下面的代碼在一個單獨的活動設置標題:mTitle1 = getName;

謝謝你非常重視你的時間。

我有一個非常好的DBAdapter通過一個教程,我也跟着提供:

public class DBAdapter { 

private static final String TAG = "DBAdapter"; //used for logging database version changes 

// Field Names: 
public static final String KEY_ROWID = "_id"; 
public static final String KEY_NAME = "name"; 
public static final String KEY_DATE = "date"; 

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_DATE}; 

// Column Numbers for each Field Name: 
public static final int COL_ROWID = 0; 
public static final int COL_NAME = 1; 
public static final int COL_DATE = 2; 

// DataBase info: 
public static final String DATABASE_NAME = "dbCharacters"; 
public static final String DATABASE_TABLE = "Character_Info"; 
// The version number must be incremented each time a change to DB structure occurs. 
public static final int DATABASE_VERSION = 2; 

//SQL statement to create database 
private static final String DATABASE_CREATE_SQL = 
     "CREATE TABLE " + DATABASE_TABLE 
     + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
     + KEY_NAME + " TEXT NOT NULL, " 
     + KEY_DATE + " TEXT" 
     + ");"; 

private final Context context; 
private DatabaseHelper myDBHelper; 
private SQLiteDatabase db; 


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 be inserted into the database. 
public long insertRow(String name, String date) { 
    ContentValues initialValues = new ContentValues(); 
    initialValues.put(KEY_NAME, name); 
    initialValues.put(KEY_DATE, date); 

    // Insert the data 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 name, String date) { 
    String where = KEY_ROWID + "=" + rowId; 
    ContentValues newValues = new ContentValues(); 
    newValues.put(KEY_NAME, name); 
    newValues.put(KEY_DATE, date); 
    // Insert it into the database. 
    return db.update(DATABASE_TABLE, newValues, where, null) != 0; 
} 


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); 
    } 
} 

public void getName (long id) { 

} 

} 

這裏的PPartisan的建議:

public String getName(long l) { 
    Cursor result = myDBHelper.getReadableDatabase().query(
      DBAdapter.DATABASE_NAME, //Name of your database 
      new String[] { DBAdapter.KEY_NAME }, //List of columns to return, as a String array. Just one in your case. 
      DBAdapter.KEY_ROWID + "=?", //The row selection criteria. Equivalent to saying "Where the key id is equal to..." 
      new String[] { String.valueOf(1) }, //...this value 
      null, //This parameter deals with grouping results. No need here, hence null. 
      null, //Relates to the above. Also null. 
      null //Orders results. There should just be one, so it's null here, but can be useful. 
    ); 

    if (result.moveToFirst()) { 
     name = result.getString(result.getColumnIndex(DBAdapter.KEY_NAME)); 
    } 
    return name; 

Zahan的建議:

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

    mCharacterInfoDrawerFragment = (CharacterInfo_Drawer_Fragment) 
      getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); 

    openDB(); 
    String name = DBAdapter.getName(1); 
    mTitle1 = name; 
    closeDB(); 


    mCharacterInfoDrawerFragment.setUp(
      R.id.navigation_drawer, 
      (DrawerLayout) findViewById(R.id.drawer_layout)); 



} 

回答

1

針對Android的SQLite數據庫檢索數據涉及與query()方法運行查詢,理想(IMO)(您也可以使用rawQuery())。由於數據庫操作可以很容易地運行很長時間(幾秒鐘),所以您希望儘可能少地查詢您的數據庫,請儘可能使查詢本身具體,並且真正將其從UI線程中導出。

如果,例如,你真的只需要訪問數據庫的一個「細胞」,那麼你將構建一個query()如下:

Cursor result = myDbInstance.getReadableDatabase().query(
    DBAdapter.DATABASE_TABLE, //Name of your table 
    new String[] { DBAdapter.KEY_NAME }, //List of columns to return, as a String array. Just one in your case. 
    DBAdapter.KEY_ID + "=?", //The row selection criteria. Equivalent to saying "Where the key id is equal to..." 
    new String[] { String.valueOf(idOfTheRowToQuery) }, //...this value 
    null, //This parameter deals with grouping results. No need here, hence null. 
    null, //Relates to the above. Also null. 
    null //Orders results. There should just be one, so it's null here, but can be useful. 
    ) 

所有這一切都將返回Cursor對象。訪問存儲在String,你會檢查,看它是否有一個條目(應該),移動到第一個(也是唯一的,在這種情況下)條目,並運行以下命令:

if (result.moveToFirst()) { 
    String name = result.getString(result.getColumnIndex(DBAdapter.KEY_NAME)); 
} 

然後你只需將其分配給您的TextView

有幾點要記住,雖然:

  1. 它通常建議使用static synchronized singleton與您的數據庫實例。有關更多信息,請參閱here
  2. 如果你真的只需要一個條目,那麼以上是好的。但是,如果您可能需要更多,那麼您應該以這樣的方式來構建您的需求,以便出於性能原因返回您需要的所有內容,並且儘可能少地返回所有內容。
  3. 數據庫操作很慢,應該在UI線程中進行。通常這是通過AsyncTask完成的,但它不是唯一的方法。如果您有興趣,我發表了一篇博客文章,其中提到了很多這些要點here
+0

嘿,在'if語句'中出現''無法解析'KEY_NAME''符號的錯誤。我將附加的代碼發佈到OP中。 – Mikitz06

+0

@ Mikitz06噢,對不起,那應該是'DBAdapter.KEY_NAME' - 我現在就改變它。 – PPartisan

+0

結果在''不能解析器符號'DBAdapter'「'另外,它說有一個'返回語句'丟失。它應該是「返回名稱」嗎? – Mikitz06

1

創建方法getName像低於

public String getName(long l) 
{ 
    String[] columns=new String[]{KEY_NAME,KEY_ROWID}; 
    Cursor c=yourDatabase.query(DATABASE_TABLE_NAME,columns,KEY_ROWID + "=" + l,null,null,null,null); 
    if(c!=null) 
    { 
    c.moveToFirst(); 
    String name=c.getString(1); // use your desired column's index instead of 1 
    return name; 
    } 
return null; 
} 

現在你可以從你的活動調用和設置的TextView利剋剋

Your_db_class object_name=new Your_db_class(); 
object_name.open();  
String mTitle1 = object_name.getName(1); //KEY_ROWID 
object_name.close(); 
textView.setText(""+mTitle1+""); 
+0

On'return name;'error of'「不兼容的類型。必需:string - 找到:java.lang.String」' – Mikitz06

+0

現在應該是okey了。我只是犯了個錯誤。代碼是okey.try現在@ Mikitz06 –

+0

編碼添加到OP。 'getName'上的錯誤顯示''非靜態方法'getName(long)'不能從靜態上下文中引用「'我試圖在一個NavigationDrawer父活動中設置ActionBar標題。 – Mikitz06