1

EDIT3:我决定将它们放入单独的文件中,因为这就是我今天早上工作时拥有它们的方式。当我检查数据库时,只显示了用户,但他们都有几乎相同的代码,除了常量值发生了变化。

更新的日志:

04-29 02:25:52.236: W/KeyCharacterMap(11342): No keyboard for id 0
04-29 02:25:52.236: W/KeyCharacterMap(11342): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
04-29 02:26:03.816: D/dalvikvm(11342): GC_EXTERNAL_ALLOC freed 1931 objects / 121640 bytes in 76ms
04-29 02:26:03.826: E/Cursor(11342): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/com.gofitness.www/databases/gofit.db, table = users, query = SELECT userid, username, password FROM users
04-29 02:26:03.826: E/Cursor(11342): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
04-29 02:26:03.826: E/Cursor(11342):    at android.database.sqlite.SQLiteCursor.<init>(SQLiteCursor.java:210)
04-29 02:26:03.826: E/Cursor(11342):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:53)
04-29 02:26:03.826: E/Cursor(11342):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
04-29 02:26:03.826: E/Cursor(11342):    at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1229)
04-29 02:26:03.826: E/Cursor(11342):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184)
04-29 02:26:03.826: E/Cursor(11342):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1264)
04-29 02:26:03.826: E/Cursor(11342):    at com.gofitness.www.logindetails.getData(logindetails.java:88)
04-29 02:26:03.826: E/Cursor(11342):    at com.gofitness.www.view.onCreate(view.java:17)
04-29 02:26:03.826: E/Cursor(11342):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-29 02:26:03.826: E/Cursor(11342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-29 02:26:03.826: E/Cursor(11342):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-29 02:26:03.826: E/Cursor(11342):    at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-29 02:26:03.826: E/Cursor(11342):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-29 02:26:03.826: E/Cursor(11342):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 02:26:03.826: E/Cursor(11342):    at android.os.Looper.loop(Looper.java:123)
04-29 02:26:03.826: E/Cursor(11342):    at android.app.ActivityThread.main(ActivityThread.java:4627)
04-29 02:26:03.826: E/Cursor(11342):    at java.lang.reflect.Method.invokeNative(Native Method)
04-29 02:26:03.826: E/Cursor(11342):    at java.lang.reflect.Method.invoke(Method.java:521)
04-29 02:26:03.826: E/Cursor(11342):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-29 02:26:03.826: E/Cursor(11342):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-29 02:26:03.826: E/Cursor(11342):    at dalvik.system.NativeStart.main(Native Method)
04-29 02:26:03.926: D/dalvikvm(11342): GC_EXTERNAL_ALLOC freed 765 objects / 66120 bytes in 61ms
04-29 02:26:09.915: I/Database(11342): sqlite returned: error code = 1, msg = no such table: Achievements
04-29 02:26:09.925: E/Database(11342): Error inserting Achievement=tyrenzo
04-29 02:26:09.925: E/Database(11342): android.database.sqlite.SQLiteException: no such table: Achievements: , while compiling: INSERT INTO Achievements(Achievement) VALUES(?);
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:36)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1145)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1536)
04-29 02:26:09.925: E/Database(11342):  at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
04-29 02:26:09.925: E/Database(11342):  at com.gofitness.www.AddAchievements.createEntry(AddAchievements.java:80)
04-29 02:26:09.925: E/Database(11342):  at com.gofitness.www.Achievements$1.onClick(Achievements.java:41)
04-29 02:26:09.925: E/Database(11342):  at android.view.View.performClick(View.java:2408)
04-29 02:26:09.925: E/Database(11342):  at android.view.View$PerformClick.run(View.java:8816)
04-29 02:26:09.925: E/Database(11342):  at android.os.Handler.handleCallback(Handler.java:587)
04-29 02:26:09.925: E/Database(11342):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 02:26:09.925: E/Database(11342):  at android.os.Looper.loop(Looper.java:123)
04-29 02:26:09.925: E/Database(11342):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-29 02:26:09.925: E/Database(11342):  at java.lang.reflect.Method.invokeNative(Native Method)
04-29 02:26:09.925: E/Database(11342):  at java.lang.reflect.Method.invoke(Method.java:521)
04-29 02:26:09.925: E/Database(11342):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-29 02:26:09.925: E/Database(11342):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-29 02:26:09.925: E/Database(11342):  at dalvik.system.NativeStart.main(Native Method)
04-29 02:26:11.776: W/KeyCharacterMap(11342): No keyboard for id 0
04-29 02:26:11.776: W/KeyCharacterMap(11342): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
04-29 02:26:14.805: I/Database(11342): sqlite returned: error code = 1, msg = no such table: Achievements
04-29 02:26:14.805: D/AndroidRuntime(11342): Shutting down VM
04-29 02:26:14.805: W/dalvikvm(11342): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-29 02:26:14.845: E/AndroidRuntime(11342): FATAL EXCEPTION: main
04-29 02:26:14.845: E/AndroidRuntime(11342): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gofitness.www/com.gofitness.www.AchievementView}: android.database.sqlite.SQLiteException: no such table: Achievements: , while compiling: SELECT AchievementID, Achievement FROM Achievements
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.os.Looper.loop(Looper.java:123)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.ActivityThread.main(ActivityThread.java:4627)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at java.lang.reflect.Method.invokeNative(Native Method)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at java.lang.reflect.Method.invoke(Method.java:521)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at dalvik.system.NativeStart.main(Native Method)
04-29 02:26:14.845: E/AndroidRuntime(11342): Caused by: android.database.sqlite.SQLiteException: no such table: Achievements: , while compiling: SELECT AchievementID, Achievement FROM Achievements
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1229)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1264)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at com.gofitness.www.AddAchievements.getData(AddAchievements.java:88)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at com.gofitness.www.AchievementView.onCreate(AchievementView.java:17)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-29 02:26:14.845: E/AndroidRuntime(11342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-29 02:26:14.845: E/AndroidRuntime(11342):    ... 11 more

这是 AddAchievement.java

 package com.gofitness.www;

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

public class AddAchievements {

    public static final String KEY_ROWID = "AchievementID";
    public static final String KEY_NAME = "Achievement";


    private static final String DATABASE_NAME = "gofit.db";
    private static final String DATABASE_TABLE = "Achievements";
    private static final int DATABASE_VERSION = 1;


    private DbHelper ourHelper;
    Context ourContext;
    private SQLiteDatabase ourDatabase;

    public class DbHelper extends SQLiteOpenHelper
    {





        public DbHelper(Context context, String name, CursorFactory factory, int version) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(
                    "CREATE TABLE " + DATABASE_TABLE + "(" + 
            KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                            KEY_NAME + " TEXT NOT NULL);"

                    );
        }

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



                    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
                    onCreate(db);
                    }

    }
    public AddAchievements(Context c)
    {
        ourContext = c; 
    }

    public AddAchievements open(){
        ourHelper = new DbHelper(ourContext, DATABASE_NAME, null, 1);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;


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

    public long createEntry(String check, String checkpass) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME,check);

        return ourDatabase.insert(DATABASE_TABLE,null, cv);

    }

    public String getData() {
        // TODO Auto-generated method stub

        String[] columns = new String[]{KEY_ROWID, KEY_NAME};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iUser = c.getColumnIndex(KEY_NAME);


        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){

        result = result + c.getString(iRow) + " " + c.getString(iUser) +"\n";
        }
        c.close();
        return result;
    }

    public String getName(String s) {
        // TODO Auto-generated method stub
        Cursor c = ourDatabase.rawQuery("SELECT * FROM " +
                DATABASE_TABLE +
                " where username = "+ "'"+ s+"'" , null);

        if (c != null ) {
            c.moveToFirst();

                 int iUsername = c.getColumnIndex(KEY_NAME);
                    String Name = c.getString(iUsername);

                   c.close();
                    return Name;

            }
        return null;
    }


}

这是 AddAchievementDB.java

package com.gofitness.www;

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

public class AddUserAchievementsDB {

    public static final String KEY_ROWID = "AchievementID";
    public static final String KEY_USERID = "user_id";
    public static final String KEY_COMPLETED = "Completed";


    private static final String DATABASE_NAME = "gofit.db";
    private static final String DATABASE_TABLE = "UserAchievementsDB";
    private static final int DATABASE_VERSION = 1;


    private DbHelper ourHelper;
    Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper
    {





        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase dbachievements) {
            // TODO Auto-generated method stub
            dbachievements.execSQL(
                    "CREATE TABLE " + DATABASE_TABLE + "(" + 
            KEY_ROWID + " INT NOT NULL,"+ 
            KEY_USERID + " INT NOT NULL," +
            KEY_COMPLETED + " TEXT NOT NULL);"

                    );
        }

        @Override
        public void onUpgrade(SQLiteDatabase dbachievements, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            if (oldVersion==2){


                    dbachievements.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
                    onCreate(dbachievements);
                    }}

    }
    public AddUserAchievementsDB(Context c)
    {
        ourContext = c; 
    }

    public AddUserAchievementsDB open(){
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;


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

    public long createEntry(String check, String checkpass, String completedDB) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_ROWID,check);
        cv.put(KEY_USERID,checkpass);
        cv.put(KEY_COMPLETED,completedDB);

        return ourDatabase.insert(DATABASE_TABLE,null, cv);

    }

    public String getData() {
        // TODO Auto-generated method stub

        String[] columns = new String[]{KEY_ROWID, KEY_USERID, KEY_COMPLETED};
         String sql = "SELECT * FROM UserAchievementsDB INNER JOIN Achievements ON UserAchievementsDB.AchievementID=Achievements.AchievementID WHERE UserAchievementsDB."+KEY_USERID+" = " + Constants.UserID + ";";

        Cursor c = ourDatabase.rawQuery(sql, null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iUser = c.getColumnIndex("username");
        int iCompleted = c.getColumnIndex(KEY_COMPLETED);


        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){

        result = result + c.getString(iRow) + " " + c.getString(iUser) + c.getString(iCompleted) + "\n";
        }
        return result;
    }

    public String getName(String s) {
        // TODO Auto-generated method stub
        Cursor c = ourDatabase.rawQuery("SELECT * FROM " +
                DATABASE_TABLE +
                " where username = "+ "'"+ s+"'" , null);

        if (c != null ) {
            c.moveToFirst();

                 int iUsername = c.getColumnIndex(KEY_USERID);
                    String Name = c.getString(iUsername);


                    return Name;

            }
        return null;
    }


}

AddStats.Java

package com.gofitness.www;

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


public class AddStats {

    public static final String KEY_ROWID = "userid";
    public static final String KEY_NAME = "username";
    public static final String KEY_WEIGHT = "weight";
    public static final String KEY_HEIGHT = "height";
    public static final String KEY_AGE = "age";
    public static final String KEY_CALORIES = "calories";
    public static final String KEY_PROTEIN = "protein";
    public static final String KEY_CARBS = "carbs";
    public static final String KEY_FATS = "fats";

    private static final String DATABASE_NAME = "gofit.db";
    private static final String DATABASE_TABLE = "stats";
    private static final int DATABASE_VERSION = 1;


    private DbHelper ourHelper;
    Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper
    {





        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase dbstats) {
            // TODO Auto-generated method stub
            dbstats.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" + 
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_AGE + " INT NOT NULL, " +
                    KEY_CALORIES + " INT NOT NULL, " +
                    KEY_WEIGHT + " INT NOT NULL, " +
                    KEY_HEIGHT + " INT NOT NULL, " +
                    KEY_PROTEIN + " INT NOT NULL, " +
                    KEY_FATS + " INT NOT NULL, " +
                    KEY_CARBS + " INT NOT NULL);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase dbstats, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            if (oldVersion==1){

            dbstats.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(dbstats);
            }

        }

    }
    public AddStats(Context c)
    {
        ourContext = c; 
    }

    public AddStats open(){
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;


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

    public long createEntry(String usernamevar, String agevar,String weightvar,String heightvar,String caloriesvar,
            String proteinvar, String carbsvar, String fatvar) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME,usernamevar);
        cv.put(KEY_AGE,agevar);
        cv.put(KEY_WEIGHT,weightvar);
        cv.put(KEY_HEIGHT,heightvar);
        cv.put(KEY_CALORIES,caloriesvar);
        cv.put(KEY_PROTEIN,proteinvar);
        cv.put(KEY_CARBS,carbsvar);
        cv.put(KEY_FATS,fatvar);

        return ourDatabase.insert(DATABASE_TABLE,null, cv);

    }

    public String getData() {
        // TODO Auto-generated method stub

        String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_AGE,KEY_WEIGHT,KEY_HEIGHT, KEY_CALORIES,KEY_PROTEIN,KEY_CARBS,KEY_FATS};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iUser = c.getColumnIndex(KEY_NAME);
        int iAge = c.getColumnIndex(KEY_AGE);
        int iWeight = c.getColumnIndex(KEY_WEIGHT);
        int iHeight = c.getColumnIndex(KEY_HEIGHT);
        int iCalories = c.getColumnIndex(KEY_CALORIES);
        int iProtein = c.getColumnIndex(KEY_PROTEIN);
        int iCarb = c.getColumnIndex(KEY_CARBS);
        int iFat = c.getColumnIndex(KEY_FATS);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){

        result = result + c.getString(iRow) + " " + c.getString(iUser) + "\n Age: " + c.getString(iAge) +"\n Weight: "+ c.getString(iWeight)+"\n Height: "
                + c.getString(iHeight) +"\n Calories: "+ c.getString(iCalories)+"\n Protein: " +c.getString(iProtein)+"\n Carb: " + c.getString(iCarb)+ "\n Fat: "+ c.getString(iFat) +"\n";
        }
        return result;
    }

    public String getUser() {
        // TODO Auto-generated method stub

        String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_AGE,KEY_WEIGHT,KEY_HEIGHT, KEY_CALORIES,KEY_PROTEIN,KEY_CARBS,KEY_FATS};
        Cursor c = ourDatabase.rawQuery("SELECT * FROM " +
                DATABASE_TABLE +
                " where username = "+ "'"+ Constants.SESSION_NAME+"'" , null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iUser = c.getColumnIndex(KEY_NAME);
        int iAge = c.getColumnIndex(KEY_AGE);
        int iWeight = c.getColumnIndex(KEY_WEIGHT);
        int iHeight = c.getColumnIndex(KEY_HEIGHT);
        int iCalories = c.getColumnIndex(KEY_CALORIES);
        int iProtein = c.getColumnIndex(KEY_PROTEIN);
        int iCarb = c.getColumnIndex(KEY_CARBS);
        int iFat = c.getColumnIndex(KEY_FATS);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            int in = Integer.valueOf(c.getString(iCalories));
            int calories = in + 300;
        result = result + c.getString(iRow) + " " + c.getString(iUser) + "\n Age: " + c.getString(iAge) +"\n Weight: "+ c.getString(iWeight)+"\n Height: "
                + c.getString(iHeight) +"\n Calories: "+ calories+"\n Protein: " +c.getString(iProtein)+"\n Carb: " + c.getString(iCarb)+ "\n Fat: "+ c.getString(iFat) +"\n";
        }
        return result;
    }

}

AddStatsForm.java

package com.gofitness.www;

import android.app.Activity;



import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class AddStatsForm extends Activity implements OnClickListener {

    EditText username, age, weight,height, calories, protein, carbs, fat;
    TextView success;
    Button submit;



     @Override
    protected void onCreate(Bundle viewInfo) {
        // TODO Auto-generated method stub
        super.onCreate(viewInfo);
        setContentView(R.layout.stats);

         submit = (Button) findViewById(R.id.bEnter);
          username = (EditText) findViewById(R.id.etUsername);
         age = (EditText) findViewById(R.id.etAge);
         weight = (EditText) findViewById(R.id.etWeight);
         height = (EditText) findViewById(R.id.etHeight);
       calories = (EditText) findViewById(R.id.etCalories);
         protein = (EditText) findViewById(R.id.etProtein);
         carbs = (EditText) findViewById(R.id.etCarbs);
          fat = (EditText) findViewById(R.id.etFat);
          success = (TextView) findViewById(R.id.tvSuccess);





   submit.setOnClickListener(this);

    }

     @Override
        public void onClick(View view) {

         boolean diditwork = true;
            try {

                String usernamevar = username.getText().toString();
                String agevar = age.getText().toString();
                String weightvar = weight.getText().toString();
                String heightvar = height.getText().toString();
                String caloriesvar = calories.getText().toString();
                String proteinvar = protein.getText().toString();
                String carbsvar = carbs.getText().toString();
                String fatvar = fat.getText().toString();

                AddStats entry = new AddStats(AddStatsForm.this);
                entry.open();
                entry.createEntry(usernamevar ,agevar, weightvar, heightvar, caloriesvar, proteinvar, carbsvar, fatvar);
                entry.close();
            }catch (Exception e){
                diditwork=false;
                }finally{
            if(diditwork){
            success.setText("WERKED");  
            }
                }
     }}
4

2 回答 2

1

为拖钓而道歉,但我认为我看到了根本问题。

AFAICT,当数据库版本号更改或数据库不存在时,仅对您的一个 DBHelper 类调用 SQLiteOpenHelper 中的 onCreate 一次;不会为您的每个单独的类调用它,而只会调用第一个类。从而创建第一个表而不是其他表。

一个(不推荐并且不确定它是否有效)修复方法是将每个表存放在单独的数据库中,然后在您的 sql 中使用dbname.tablename来访问它们。


从您的代码中,我有点不确定您希望采用的整体设计模式,因此其余部分可能有点离题:

如果您想“根据需要”创建表,最好在 SQL 中检查表是否存在,如果不存在则创建它。(低效但可靠)

/** does table exist? **/
private boolean txists(SQLiteDatabase db, String tableName) {
    Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
    if (cursor != null) {
        if (cursor.getCount() > 0) {
            cursor.close();
            return true;
        }
        cursor.close();
    }
    return false;
}

否则,从我读过的所有内容来看,各种 DBHelpers 的模式似乎都是单例

private static MYDBHelper dbhelper = null;
public MYDBHelper getDBHelper(){
    if( dbhelper == null ){
        dbhelper = newInstance(...);
        ...
    }
    return dbhelper;
}

如果您正在尝试实现“可插拔”架构,在每个类中封装表规范和创建;考虑从单个 DBHelper 类而不是每个插件类(AddAchievements 和 AddStats)中的一个 dbhelper 使用的接口和钩子。

最后,您可能希望将 ContentProvider 视为访问数据的一种方式(是的,我知道它看起来像一个不必要的抽象层和复杂性,但是当您扩展和扩展应用程序的功能时它是有意义的,尤其是当与其他服务交谈、添加搜索、通知等时;它还提供了一个集中的位置来放置您的 DBHelper、表创建等)

于 2013-04-29T11:24:39.343 回答
0

我可能是盲人,但在我的模拟器中找不到这个“擦除用户数据”来检查它是如何工作的。

检查 DDMS 文件资源管理器目录 /data/data/your.app.name/databases 从那里删除所有文件并再次运行应用程序。

您的表格名称全部小写,但在出现错误时,您使用首字母大写。为表名创建常量,就像您对列所做的那样,并使用它们来避免混淆

//编辑

您现在提供的代码与以前的代码完全不同,这个代码无法正常工作。DBHelper 对所有表都是通用的,但您将它们分开。结果,您只有一个表用户,因为这是您首先访问的表。

如果您希望将所有表保存在单独的类中,您必须将 DbHelper 类分开,而不是为它们中的每一个创建内部类。

于 2013-04-28T23:32:11.420 回答