选择数据库行android app SQLite

时间:2012-08-21 07:05:23

标签: android database sqlite

我在Android应用中创建了一个数据库。以下是我创建它的方法。

DatabaseHelper.java:

public class DatabaseHelper extends SQLiteOpenHelper {

static final String dbName="db_dr.droid";

static final String MedhistTable="tbl_medhist";
static final String colName="MedHistName";
static final String colAge="MedHistAge";
static final String colWeight="MedHistWeight";
static final String colHeight="MedHistHeight";
static final String colMedHist="MedHistHist";

static final String DTipsTable="tbl_dailytips";
static final String colID="DTipsId";
static final String colText="DTipsText";

static final String viewHist="ViewHist";

public DatabaseHelper(Context context) {
      super(context, dbName, null,33); 
      }

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

    db.execSQL("CREATE TABLE "+MedhistTable+" ("+colName+ " TEXT , "+
            colAge + " INTEGER, " +
            colWeight + " INTEGER, " +
            colHeight + " INTEGER, " +
            colMedHist + " TEXT) ");

    db.execSQL("CREATE TABLE "+DTipsTable+" ("+colID+ " INTEGER , "+
            colText + " TEXT)");


     db=this.getWritableDatabase();
     ContentValues cv=new ContentValues();
       cv.put(colID, 1);
       cv.put(colText, "It's easy to fit physical activities into your daily routine. Walk, bike or jog to see friends. Take a 10-minute activity break every hour while you read, do homework or watch TV. Climb stairs instead of taking an escalator or elevator. Try to do these things for a total of 30 minutes every day.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 2);
       cv.put(colText, "Breakfast fills your 'empty tank' to get you going after a long night without food. And it can help you do better in school. Easy to prepare breakfasts include cold cereal with fruit and low-fat milk, whole-wheat toast with peanut butter, yogurt with fruit, whole-grain waffles or even last night's pizza!");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 3);
       cv.put(colText, "Snacks are a great way to refuel. Choose snacks from different food groups - a glass of low-fat milk and a few graham crackers, an apple or celery sticks with peanut butter and raisins, or some dry cereal. If you eat smart at other meals, cookies, chips and candy are OK for occasional snacking.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 4);
       cv.put(colText, "Vigorous work-outs - when you're breathing hard and sweating - help your heart pump better, give you more energy and help you look and feel best. Start with a warm-up that stretches your muscles. Include 20 minutes of aerobic activity, such as running, jogging, or dancing. Follow-up with activities that help make you stronger such as push-ups or lifting weights. Then cool-down with more stretching and deep breathing.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 5);
       cv.put(colText, "Vigorous work-outs - when you're breathing hard and sweating - help your heart pump better, give you more energy and help you look and feel best. Start with a warm-up that stretches your muscles. Include 20 minutes of aerobic activity, such as running, jogging, or dancing. Follow-up with activities that help make you stronger such as push-ups or lifting weights. Then cool-down with more stretching and deep breathing.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 6);
       cv.put(colText, "Being active is much more fun with friends or family. Encourage others to join you and plan one special physical activity event, like a bike ride or hiking, with a group each week.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 7);
       cv.put(colText, "Eat more grains, fruits and vegetables. These foods give you carbohydrates for energy, plus vitamins, minerals and fiber. Besides, they taste good! Try breads such as whole-wheat, bagels and pita. Spaghetti and oatmeal are also in the grain group." +
               "Bananas, strawberries and melons are some great tasting fruits. Try vegetables raw, on a sandwich or salad.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 8);
       cv.put(colText, "Whether you take a physical education class or do other physical activities at school, such as intramural sports, structures activities are a sure way to feel good, look good and stay physically fit.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 9);
       cv.put(colText, "A healthy eating style is like a puzzle with many parts. Each part -- or food -- is different. Some foods may have more fat, sugar or salt while others may have more vitamins or fiber. There is a place for all these foods. What makes a diet good or bad is how foods fit together. Balancing your choices is important. Fit in a higher-fat food, like pepperoni pizza, at dinner by choosing lower-fat foods at other meals. And don't forget about moderation. If two pieces of pizza fill you up, you don't need a third.");
       db.insert(DTipsTable, colID, cv);

       cv.put(colID, 10);
       cv.put(colText, "Take advantage of physical activities you and your friends enjoy doing together and eat the foods you like. Be adventurous - try new sports, games and other activities as well as new foods. You'll grow stronger, play longer, and look and feel better! Set realistic goals - don't try changing too much at once.");
       db.insert(DTipsTable, colID, cv);

       db.close();

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS "+ MedhistTable);

    db.execSQL("DROP TABLE IF EXISTS "+ DTipsTable);

    db.close();
}

String getTips()
  {

   SQLiteDatabase db=this.getReadableDatabase();

  // Cursor cur=db.rawQuery("SELECT "+ colID +" as _id," + colText + "from "+ DTipsTable + "WHERE ",new String [] {});

   Cursor c=db.query(DTipsTable, new String[]{colID+" as _id",colText},
           colID+"=?", new String[]{colText}, null, null, null);

   c.moveToFirst();
   db.close();
   c.close();
   return c.getString(c.getColumnIndex("colText"));  

  }

}

在我的home.java中,我调用数据库助手来检索特定的行。

public class Home extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
DatabaseHelper dbhelp = new DatabaseHelper(this);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);


      String tips = dbhelp.getTips();


    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Daily Health Tips")
    .setMessage(tips)
    .setCancelable(false)
    .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();

    alert.show();


}

但该应用程序正在停止。这是Catlog

    08-21 16:04:48.588: E/Trace(630): error opening trace file: No such file or directory (2)
08-21 16:04:48.958: D/dalvikvm(630): GC_FOR_ALLOC freed 258K, 4% free 8142K/8455K, paused 69ms, total 73ms
08-21 16:04:49.078: D/dalvikvm(630): GC_FOR_ALLOC freed 194K, 5% free 8257K/8647K, paused 44ms, total 54ms
08-21 16:04:49.218: D/AndroidRuntime(630): Shutting down VM
08-21 16:04:49.218: W/dalvikvm(630): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08-21 16:04:49.228: E/AndroidRuntime(630): FATAL EXCEPTION: main
08-21 16:04:49.228: E/AndroidRuntime(630): java.lang.RuntimeException: Unable to start activity ComponentInfo{dr.droid/dr.droid.Home}: java.lang.IllegalStateException: getDatabase called recursively
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.os.Looper.loop(Looper.java:137)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.ActivityThread.main(ActivityThread.java:4745)
08-21 16:04:49.228: E/AndroidRuntime(630):  at java.lang.reflect.Method.invokeNative(Native Method)
08-21 16:04:49.228: E/AndroidRuntime(630):  at java.lang.reflect.Method.invoke(Method.java:511)
08-21 16:04:49.228: E/AndroidRuntime(630):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-21 16:04:49.228: E/AndroidRuntime(630):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-21 16:04:49.228: E/AndroidRuntime(630):  at dalvik.system.NativeStart.main(Native Method)
08-21 16:04:49.228: E/AndroidRuntime(630): Caused by: java.lang.IllegalStateException: getDatabase called recursively
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:204)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
08-21 16:04:49.228: E/AndroidRuntime(630):  at dr.droid.DatabaseHelper.onCreate(DatabaseHelper.java:44)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
08-21 16:04:49.228: E/AndroidRuntime(630):  at dr.droid.DatabaseHelper.getTips(DatabaseHelper.java:104)
08-21 16:04:49.228: E/AndroidRuntime(630):  at dr.droid.Home.onCreate(Home.java:20)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.Activity.performCreate(Activity.java:5008)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-21 16:04:49.228: E/AndroidRuntime(630):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-21 16:04:49.228: E/AndroidRuntime(630):  ... 11 more
08-21 16:04:52.138: I/Process(630): Sending signal. PID: 630 SIG: 9

任何帮助/建议将不胜感激!谢谢!

3 个答案:

答案 0 :(得分:0)

你必须在创建函数

之后或之后初始化dbhelp变量

答案 1 :(得分:0)

试试这个:

public class Home extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    DatabaseHelper dbhelp = new DatabaseHelper(this);
     String tips = dbhelp.getTips();


    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Daily Health Tips")
    .setMessage(tips)
    .setCancelable(false)
    .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();

    alert.show();


}

您应该尝试在Home类中移动getTips()方法。这样你的代码看起来会更清晰。

答案 2 :(得分:0)

您的sql包含错误:

  db.execSQL("CREATE TABLE "+MedhistTable+" ("+colName+ " TEXT , "+
            colAge + " INTEGER +)" +
            colWeight + " INTEGER " +
            colHeight + " INTEGER " +
            colMedHist + " TEXT ");

    db.execSQL("CREATE TABLE "+DTipsTable+" ("+colID+ " INTEGER , "+
            colText + " TEXT +)");

应该是

  db.execSQL("CREATE TABLE "+MedhistTable+" ("+colName+ " TEXT , "+
            colAge + " INTEGER, " +
            colWeight + " INTEGER, " +
            colHeight + " INTEGER, " +
            colMedHist + " TEXT) ");

    db.execSQL("CREATE TABLE "+DTipsTable+" ("+colID+ " INTEGER , "+
            colText + " TEXT)");