将sqlite数据库从pc复制到android?

时间:2012-05-09 23:02:50

标签: android sqlite

请问如何在真正的Android手机中使用数据库(我使用Eclipse创建并使用SDK)? 该应用程序运行良好,但当我需要从搜索栏访问数据库时,它只是崩溃。 我真的需要这个为我明天的顶点。

package com.nutriapp;

import java.util.ArrayList;
import java.util.Date;

import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;

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.SQLiteOpenHelper;
import android.util.Log;

公共类DatabaseAdapter {

public static final String COLUMN_ID = "ID";
public static final String COLUMN_NAME = "Name";
public static final String COLUMN_AGE = "Age";
public static final String COLUMN_GENDER = "Gender";
public static final String COLUMN_WEIGHT = "Weight";
public static final String COLUMN_HEIGHT = "Height";
public static final String COLUMN_ACTIVITY = "Activitylevel";
public static final String COLUMN_CALORIES = "numCal";
public static final String FOOD_ID = "food_ID";
public static final String FOOD_NAME = "food_name";
public static final String FOOD_CALS = "food_cals";
public static final String FOOD_FAT = "food_fat";
public static final String FOOD_PRO = "food_protein";
public static final String FOOD_CRAB = "food_crabs";
public static final String EXERCISE_NAME = "exercise_name";
public static final String EXERCISE_CALS = "exercise_cals";
public static final String EXERCISE_ID = "exercise_ID";
public static final String DAILY_ID = "daily_ID";
public static final String DAILY_DATE = "daily_date";
public static final String DAILY_FAT = "daily_fat";
public static final String DAILY_PROTS = "daily_protein";
public static final String DAILY_CARBS = "daily_carb";
public static final String DAILY_BFITEMS = "daily_breakfast";
public static final String DAILY_LNITEMS = "daily_lunch";
public static final String DAILY_DNITEMS = "daily_dinner";
public static final String DAILY_EXERCISE = "daily_exercise";

public static final String TABLE_DAILYSTATS = "dailystats";
public static final String TABLE_USERS = "users";
public static final String TABLE_FOOD = "food";
public static final String TABLE_EXERCISE = "exercise";
private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "nutriwellness.db";

private static final String CREATE_TABLE_USERS = "create table users( id integer primary key autoincrement, "
        + "Name text, Age integer, Gender text, Weight text, Height text, Activitylevel text, numCal float );";

private static final String CREATE_TABLE_FOOD = "create table food( food_ID integer primary key,"
        + "food_name text,food_cals real, food_fat real, food_protein real, food_crabs real );";

private static final String CREATE_TABLE_EXERCISE = "create table exercise( exercise_ID integer primary key,"
        + "exercise_name text,exercise_cals real );";

private static final String CREATE_TABLE_DAILYSTATS = "create table dailystats( daily_ID integer primary key autoincrement,"
        + "daily_date text, daily_fat real, daily_protein real, daily_carb real, daily_breakfast text, daily_lunch text, daily_dinner text, daily_exercise text, ID integer );";

private SQLiteDatabase database;
private DatabaseHelper dbHelper;

private String[] allColumnsofuserstable = { COLUMN_ID, COLUMN_NAME,
        COLUMN_AGE, COLUMN_GENDER, COLUMN_WEIGHT, COLUMN_HEIGHT,
        COLUMN_CALORIES };

private String[] allColumnoffoodtable = { FOOD_ID, FOOD_NAME, FOOD_FAT,
        FOOD_PRO, FOOD_CRAB };
private String[] allColumnofexercisetable = { EXERCISE_ID, EXERCISE_NAME,
        EXERCISE_CALS };

private String[] allColumnofdailytable = { DAILY_ID, DAILY_FAT,
        DAILY_PROTS, DAILY_CARBS, DAILY_EXERCISE };

public DatabaseAdapter(Context context) {

    dbHelper = new DatabaseHelper(context);
}

public static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 18);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            // db.execSQL(CREATE_TABLE_USERS);
            // db.execSQL(CREATE_TABLE_FOOD);
            // db.execSQL(CREATE_TABLE_EXERCISE);
            db.execSQL(CREATE_TABLE_DAILYSTATS);
        } catch (SQLException e) {
            // e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading database from version " + oldVersion
                        + "to version " + newVersion);

        // db.execSQL("DROP TABLE IF EXISTS users");
        // db.execSQL("DROP TABLE IF EXISTS food");
        // db.execSQL("DROP TABLE IF EXISTS exercise");
        db.execSQL("DROP TABLE IF EXISTS dailystats");

        onCreate(db);

    }

}

public float sumCalories(String[] items) {
    float sum = .0f;
    for (int i = 0; i < items.length; i++) {
        Cursor c = database.rawQuery(
                "select food_cals from food where food_name='" + items[i]
                        + "'", null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            sum += c.getFloat(0);
            c.moveToNext();
        }
    }
    return sum;
}

public float sumProteins(String[] items) {
    float sum = .0f;
    for (int i = 0; i < items.length; i++) {
        Cursor c = database.rawQuery(
                "select food_protein from food where food_name='"
                        + items[i] + "'", null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            sum += c.getFloat(0);
            c.moveToNext();
        }
    }
    return sum;
}

public float sumFat(String[] items) {
    float sum = .0f;
    for (int i = 0; i < items.length; i++) {
        Cursor c = database.rawQuery(
                "select food_fat from food where food_name='" + items[i]
                        + "'", null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            sum += c.getFloat(0);
            c.moveToNext();
        }
    }
    return sum;
}

public float sumCarbs(String[] items) {
    float sum = .0f;
    for (int i = 0; i < items.length; i++) {
        Cursor c = database.rawQuery(
                "select food_crabs from food where food_name='" + items[i]
                        + "'", null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            sum += c.getFloat(0);
            c.moveToNext();
        }
    }
    return sum;
}

public float sumBurned(String[] items) {
    float sum = .0f;
    for (int i = 0; i < items.length; i++) {
        Cursor c = database.rawQuery(
                "select exercise_cals from exercise where exercise_name='"
                        + items[i] + "'", null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            sum += c.getFloat(0);
            c.moveToNext();
        }
    }
    return sum;
}

// //////////////////////////// FOR STORING IN DAILY TABLE
public long saveDayStatistics(float fat, float protein, float carbs,
        String breakfast, String lunch, String dinner, String exercise) {
    Date now = new Date();

    ContentValues values = new ContentValues();
    values.put("daily_date", now.toString());
    values.put("daily_fat", fat);
    values.put("daily_protein", protein);
    values.put("daily_carb", carbs);
    values.put("daily_breakfast", breakfast);
    values.put("daily_lunch", lunch);
    values.put("daily_dinner", dinner);
    values.put("daily_exercise", exercise);

    return database.insert(TABLE_DAILYSTATS, DAILY_DATE, values);

}

public DatabaseAdapter open() throws SQLException {
    database = dbHelper.getWritableDatabase();
    return this;
}

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

// create a user
public long createUser(String name, String age, String gender,
        String weight, String height, String level, float calnum) {

    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, name);
    values.put(COLUMN_AGE, age);

    values.put(COLUMN_GENDER, gender);

    values.put(COLUMN_WEIGHT, weight);
    values.put(COLUMN_HEIGHT, height);
    values.put(COLUMN_ACTIVITY, level);
    values.put(COLUMN_CALORIES, calnum);

    return database.insert(TABLE_USERS, COLUMN_ID, values);
}

// delete a user by ID
public boolean deleteUser(long rowId) {
    return database.delete(TABLE_USERS, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieve a list of all users
public Cursor getAllUsers() {
    return database.query(TABLE_USERS, allColumnsofuserstable, null, null,
            null, null, null);

}

// retrieve a particular user
public Cursor getUser(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_USERS,
            allColumnsofuserstable, COLUMN_ID + "=" + rowId, null, null,
            null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

// update a user
public boolean updateUser(long rowId, String Name, int age, String gender,
        String weight, String height, String level, float calnum) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, Name);
    values.put(COLUMN_AGE, age);

    values.put(COLUMN_GENDER, gender);

    values.put(COLUMN_WEIGHT, weight);
    values.put(COLUMN_HEIGHT, height);
    values.put(COLUMN_ACTIVITY, level);
    values.put(COLUMN_CALORIES, calnum);
    return database.update(TABLE_USERS, values, COLUMN_ID + "=" + rowId,
            null) > 0;
}

// FOOD METHODS !

// Create a new food row
public long createFood(String name, double food_cal, double food_fat,
        double food_proteins, double food_carbs) {
    ContentValues Fvalues = new ContentValues();
    Fvalues.put(FOOD_NAME, name);
    Fvalues.put(FOOD_CALS, food_cal);
    Fvalues.put(FOOD_FAT, food_fat);
    Fvalues.put(FOOD_PRO, food_proteins);
    Fvalues.put(FOOD_CRAB, food_carbs);
    return database.insert(TABLE_FOOD, FOOD_ID, Fvalues);
}

// delete a Food by ID
public boolean deleteFood(long rowId) {
    return database.delete(TABLE_FOOD, FOOD_ID + "=" + rowId, null) > 0;
}

// retrieve a list of all FOOD
public ArrayList<String> getAllfood() {
    Cursor c = database.query(TABLE_FOOD, allColumnoffoodtable, null, null,
            null, null, null);
    ArrayList<String> food = new ArrayList<String>();

    c.moveToFirst();
    while (!c.isAfterLast()) {
        food.add(c.getString(1));
        c.moveToNext();
    }

    return food;

}

// Retrieve a specific Food

public Cursor getFood(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_FOOD, allColumnoffoodtable,
            FOOD_ID + "=" + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

// Update a food

public boolean updateFood(long rowId, String name, int food_cal,
        int food_fat, int food_proteins, int food_carbs) {
    ContentValues Fvalues = new ContentValues();
    Fvalues.put(FOOD_NAME, name);
    Fvalues.put(FOOD_CALS, food_cal);
    Fvalues.put(FOOD_FAT, food_fat);
    Fvalues.put(FOOD_PRO, food_proteins);
    Fvalues.put(FOOD_CRAB, food_carbs);
    return database
            .update(TABLE_FOOD, Fvalues, FOOD_ID + "=" + rowId, null) > 0;
}

// //////////////////////////////// EXERCISE
// TABLE///////////////////////////////////////////////////

public long createExercise(String name, double exercise_cals) {
    ContentValues Fvalues = new ContentValues();
    Fvalues.put(EXERCISE_NAME, name);
    Fvalues.put(EXERCISE_CALS, exercise_cals);

    return database.insert(TABLE_EXERCISE, EXERCISE_ID, Fvalues);
}

public Cursor getExercise(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_EXERCISE,
            allColumnofexercisetable, EXERCISE_ID + "=" + rowId, null,
            null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

public ArrayList<String> getAllexercise() {
    Cursor c = database.query(TABLE_EXERCISE, allColumnofexercisetable,
            null, null, null, null, null);
    ArrayList<String> exercise = new ArrayList<String>();

    c.moveToFirst();
    while (!c.isAfterLast()) {
        exercise.add(c.getString(1));
        c.moveToNext();
    }

    return exercise;

}

public boolean deleteexercise(long rowId) {
    return database.delete(TABLE_EXERCISE, EXERCISE_ID + "=" + rowId, null) > 0;
}

public XYMultipleSeriesDataset getFatDataset() {

    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    Cursor c = database.rawQuery(
            "select * from dailystats order by daily_ID desc LIMIT 7;",
            null);
    float i = 1.0f;

    c.moveToFirst();
    XYSeries seriesFat = new XYSeries("Fat");
    while (!c.isAfterLast()) {
        seriesFat.add(i++, c.getDouble(2));

        c.moveToNext();
    }
    dataset.addSeries(seriesFat);
    return dataset;
}

public XYMultipleSeriesDataset getProtDataset() {

    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    Cursor c = database.rawQuery(
            "select * from dailystats order by daily_ID desc LIMIT 7;",
            null);

    float i = 1.0f;
    c.moveToFirst();
    XYSeries seriesProtein = new XYSeries("Protein");
    while (!c.isAfterLast()) {

        seriesProtein.add(i++, c.getDouble(3));

        c.moveToNext();
    }
    dataset.addSeries(seriesProtein);
    return dataset;

}

public XYMultipleSeriesDataset getCarbsDataset() {
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    Cursor c = database.rawQuery(
            "select * from dailystats order by daily_ID desc LIMIT 7;",
            null);
    float i = 1.0f;

    c.moveToFirst();
    XYSeries seriesCarbs = new XYSeries("Carbs");
    while (!c.isAfterLast()) {

        seriesCarbs.add(i++, c.getDouble(4));

        c.moveToNext();
    }
    dataset.addSeries(seriesCarbs);
    return dataset;
}

public void clearDailyStats() {
     database.execSQL("delete from dailystats");
     Log.d("db", "lol");
}

}

2 个答案:

答案 0 :(得分:0)

另一个答案,this example显示了解决问题的快捷方法。

作为补充,您的一些代码可能会简化如下:

public float sumProteins(String[] items) {
    float sum = .0f;
    for (int i = 0; i < items.length; i++) {
        Cursor c = database.rawQuery(
                "select SUM(food_protein) from food where food_name='"
                        + items[i] + "'", null);
        if (c.moveToFirst()) {
            sum += c.getFloat(0);
        }
    }
    return sum;
}

您可以通过构建select SUM(food_protein ) from food where food_name=items[0] OR food_name=items[1] OR ...之类的查询字符串来进一步改进代码,这样您只需要执行一次查询。

此外,它是carbs而不是crabs

答案 1 :(得分:0)

您也可以将它放在/ res / raw文件夹中,并在应用程序第一次启动时将其复制。