2013-01-02 4 views
0

나는 sqlite 데이터베이스 용 안드로이드 SDK에 대한 정보와 문서를 연구 해왔다. 예제에서 찾은 데이터베이스 클래스는 here입니다. AddMed가 활동을 확장 공용 클래스가 OnClickListener를 {안드로이드 : sqlite 데이터베이스에서 데이터를 가져 오는 방법

Button submit; 
    EditText name, dossage; 
    DBAdapter database; 
    String names, amount; 
    String total; 
    ArrayList<String> btr; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.addmed); 
     submit = (Button) findViewById(R.id.bSubmit); 
     name = (EditText) findViewById(R.id.etNameOfMed); 
     dossage = (EditText) findViewById(R.id.etHowMuch); 
    } 

    @Override 
    public void onClick(View arg0) { 
     // TODO Auto-generated method stub 
     switch (arg0.getId()) { 
     case R.id.bSubmit: 
      names = name.getText().toString(); 
      amount = dossage.getText().toString(); 
      total = names + amount; 
      btr.add(total); 
      database.open(); 
      database.insertEntry(btr, btr); 
      database.close(); 
      break; 
     } 
    } 

} 

그때 내가 시도 텍스트 뷰와 다른 클래스가 구현 :

package com.example.medtracker; 

import java.sql.Timestamp; 
import java.util.ArrayList; 
import java.util.Calendar; 

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

public class DBAdapter { 
    private static final String DATABASE_NAME = "meds.db"; 
    private String DATABASE_TABLE; 
    private static final int DATABASE_VERSION = 1; 

    // Index Key column 
    public static final String KEY_ID = "_id"; 

    // Name of the column index of each column in DB 
    public ArrayList<String> TABLE_KEYS = new ArrayList<String>(); 
    public ArrayList<String> TABLE_OPTIONS = new ArrayList<String>(); 
    public final String KEY_TIMESTAMP = "timeStamp"; 
    public final int TIMESTAMP_COLUMN = 1; 

    // Create new database 
    private String DATABASE_CREATE; 

    // Variable to hold database instant 
    private SQLiteDatabase db; 

    // Database open/upgrade helper 
    private myDBHelper dbHelper; 

    public DBAdapter(Context context, String table, ArrayList<String> keys, 
      ArrayList<String> options) { 
     // Start initializing all of the variables 
     DATABASE_TABLE = table; 
     TABLE_KEYS = (ArrayList<String>) keys.clone(); 
     TABLE_OPTIONS = options; 

     String keyString = ""; 
     for (int i = 0; TABLE_KEYS.size() > i; i++) { 

      // Add commas to the options elements if there is a next value. 
      if (i + 1 < TABLE_OPTIONS.size() && TABLE_OPTIONS.get(i) != null) { 
       TABLE_OPTIONS.set(i, TABLE_OPTIONS.get(i) + ","); 
      } else if (i + 1 == TABLE_OPTIONS.size() 
        && TABLE_OPTIONS.get(i) != null) { 
       if (i + 1 < TABLE_KEYS.size()) { 
        TABLE_OPTIONS.set(i, TABLE_OPTIONS.get(i) + ","); 
       } else { 
        TABLE_KEYS.set(i, TABLE_KEYS.get(i) + ""); 
       } 
      } else if (i + 1 != TABLE_KEYS.size()) { 
       TABLE_KEYS.set(i, TABLE_KEYS.get(i) + ","); 
      } else { 
       TABLE_KEYS.set(i, TABLE_KEYS.get(i) + ""); 
      } 

      System.out.println(TABLE_OPTIONS.toString()); 
      System.out.println(TABLE_KEYS.toString()); 

      if (i + 1 <= TABLE_OPTIONS.size() && TABLE_OPTIONS.get(i) != null) 
       keyString = keyString + " " + TABLE_KEYS.get(i) + " " 
         + TABLE_OPTIONS.get(i); 
      else if (i + 1 > TABLE_OPTIONS.size() 
        || TABLE_OPTIONS.get(i) == null) { 
       keyString = keyString + " " + TABLE_KEYS.get(i); 
      } 
     } 

     // Create the database creation string. 
     DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + " (" 
       + "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
       + KEY_TIMESTAMP + "," + keyString + ");"; 

     // Create a new Helper 
     dbHelper = new myDBHelper(context, DATABASE_NAME, null, 
       DATABASE_VERSION, DATABASE_TABLE, DATABASE_CREATE); 
    } 

    public DBAdapter open() throws SQLException { 
     db = dbHelper.getWritableDatabase(); 
     return this; 
    } 

    public void close() { 
     db.close(); 
    } 

    public long insertEntry(ArrayList<String> key, ArrayList<String> value) { 
     String timeStamp = new Timestamp(Calendar.getInstance() 
       .getTimeInMillis()).toString(); 
     ContentValues contentValues = new ContentValues(); 
     for (int i = 0; key.size() > i; i++) { 
      contentValues.put(key.get(i), value.get(i)); 
     } 
     contentValues.put(KEY_TIMESTAMP, timeStamp); 
     return db.insert(DATABASE_TABLE, null, contentValues); 
    } 

    public boolean removeEntry(long rowIndex) { 
     return db.delete(DATABASE_TABLE, KEY_ID + "=" + rowIndex, null) > 0; 
    } 

    public Cursor getAllEntries(String[] columns, String selection, 
      String[] selectionArgs, String groupBy, String having, 
      String sortBy, String sortOption) { 
     return db.query(DATABASE_TABLE, columns, selection, selectionArgs, 
       groupBy, having, sortBy + " " + sortOption); 
    } 

    public int updateEntry(long rowIndex, ArrayList<String> key, 
      ArrayList<String> value) { 
     String timeStamp = new Timestamp(Calendar.getInstance() 
       .getTimeInMillis()).toString(); 
     String where = KEY_ID + "=" + rowIndex; 
     ContentValues contentValues = new ContentValues(); 
     for (int i = 0; key.size() > i; i++) { 
      contentValues.put(key.get(i), value.get(i)); 
     } 
     contentValues.put(KEY_TIMESTAMP, timeStamp); 
     return db.update(DATABASE_TABLE, contentValues, where, null); 
    } 

    public boolean clearTable() { 
     return db.delete(DATABASE_TABLE, null, null) > 0; 
    } 

    private static class myDBHelper extends SQLiteOpenHelper { 
     private String creationString; 
     private String tableName; 
     @SuppressWarnings("unused") 
     SQLiteDatabase db; 

     /** 
     * Creates a myDBHelper object. 
     * 
     * @param context 
     *   The context where the access is needed 
     * @param name 
     *   Name of database file 
     * @param factory 
     *   A CursorFactory, or null to use default CursorFactory 
     * @param version 
     *   Database version 
     * @param tableName 
     *   Name of table within database 
     * @param creationString 
     *   SQL String used to create the database 
     */ 
     public myDBHelper(Context context, String name, CursorFactory factory, 
       int version, String tableName, String creationString) { 
      super(context, name, factory, version); 
      this.creationString = creationString; 
      this.tableName = tableName; 
     } 

     /** 
     * Creates the database table. 
     * 
     * @param db 
     *   The database used by this helper to create the table in 
     */ 
     @Override 
     public void onCreate(SQLiteDatabase db) { 
      db.execSQL(creationString); 
     } 

     /** 
     * This method determines if the database needs to be updated or not. 
     * 
     * @param db 
     *   The database used by this helper 
     * @param oldVersion 
     *   The old database version 
     * @param newVersion 
     *   The new database version 
     */ 
     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      // Log the version upgrade 
      Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion 
        + " to " + newVersion + ", which will destroy all old data"); 
      db.execSQL("DROP TABLE IF EXISTS " + tableName); 
      onCreate(db); 

     } 

     /** 
     * Creates tables when the database is opened if the tables need to be 
     * created. 
     * 
     * @param db 
     *   The database used by this helper 
     */ 
     @Override 
     public void onOpen(SQLiteDatabase db) { 
      db.execSQL(creationString); 
     } 

    } 
} 

내가 다음 개체를 추가 할 클래스를 만들어이 내 클래스 새 DBAdatper 인스턴스를 만들고 커서에서 getAllEntries 메서드를 사용하지만 매개 변수를 혼동합니다. 누군가가 나를 계몽 할 수 있습니까? 도와 줘서 고마워.

답변

4

. 이 예는 getAllEntries의 각 매개 변수가 무엇인지 나열합니다. 많은 매개 변수가있는 것처럼 보이지만 결과 세트를 그룹화하거나 정렬하지 않으려는 경우 null 중 하나 일 수 있습니다. 여기에 SQLLiteDatabaseAPI에서 가져온 각 매개 변수가하는 일의 목록입니다 :

SQLiteDatabase documentation for query

public Cursor query (String table, String[] columns, String selection, String[] 
selectionArgs, String groupBy, String having, String orderBy, String limit) 

Added in API level 1 

Query the given table, returning a Cursor over the result set. 

Parameters 

table  The table name to compile the query against. 

columns  A list of which columns to return. Passing null will return all 
      columns, which is discouraged to prevent reading data from storage 
      that isn't going to be used. 

selection A filter declaring which rows to return, formatted as an SQL WHERE 
      clause (excluding the WHERE itself). Passing null will return all rows for 
      the given table. 

selectionArgs You may include ?s in selection, which will be replaced by the 
       values from selectionArgs, in order that they appear in the 
       selection. The values will be bound as Strings. 

groupBy  A filter declaring how to group rows, formatted as an SQL GROUP BY 
      clause (excluding the GROUP BY itself). Passing null will cause the rows 
      to not be grouped. 

having  A filter declare which row groups to include in the cursor, if row 
      grouping is being used, formatted as an SQL HAVING clause (excluding the 
      HAVING itself). Passing null will cause all row groups to be included, 
      and is required when row grouping is not being used. 

orderBy  How to order the rows, formatted as an SQL ORDER BY clause (excluding 
      the ORDER BY itself). Passing null will use the default sort order, which 
      may be unordered. 

limit  Limits the number of rows returned by the query, formatted as LIMIT 
      clause. Passing null denotes no LIMIT clause. 
에서

enter image description here

+0

고맙습니다. – JohnnyWineShirt

+0

문제 없으니 기꺼이 도와주세요. –

1

찾은 자습서는 자동으로 많은 것을 시도하는 수업을 제공합니다. 알기 만하면 좋지만 그렇지 않은 경우에는 좋지는 않습니다.

이 예제는 매우 복잡하며, 처음부터 직접 작성하는 것이 좋습니다. http://www.vogella.com/는 SQLite는 데이터베이스를 포함하여 좋은 자습서의 큰 컬렉션이 있습니다 SQLite 그것은 당신이 단순히 SQLLiteDatabase 클래스의 래퍼 역할을하려고 참조 예처럼 보인다

+0

답장을 보내 주셔서 감사합니다. – JohnnyWineShirt

0

하면, Y를 X라는 세 개의 열이 표라는 테이블을 가지고 말은, 지. 그리고 다음 진술을 원했습니다.

SELECT x,y FROM table1 WHERE x = 'squirrels' AND y = 'cats'; 

테이블 매개 변수는 테이블 ("table1")의 이름입니다. columns 매개 변수는 값을 가져 오는 데 관심이있는 열입니다 (이 경우 "x"및 "y"열). 선택 매개 변수는 "x =? AND y =?"입니다. selectionArgs 매개 변수는 "squirrels"및 "cats"가 포함 된 배열입니다. 나머지는 SQL을 아는 경우 자체 설명입니다.

관련 문제