1

我正在尝试将数据插入数据库,它在模拟器中工作,但是当我尝试在设备上工作时,它没有插入数据。

数据库助手类

 import android.database.sqlite.SQLiteDatabase;
    import android.util.Log;

    public class DataBaseHelper {

    SQLiteDatabase dbe;

    public DataBaseHelper(Context mycontext, String getPackageName) {

        copyDB(mycontext, getPackageName);// This method helps to copy the database from asserts to mobile

    }

    void copyDB(Context mycontext, String getPackageName) {
        try {

            String destPath = "data/data/" + getPackageName + "/databases";//this is the path for the database to save

            Log.v("opendb", "destPath: " + destPath);

            File f3 = new File(destPath);// initiating new file in destination path
            if (!f3.exists()) {         // this loop helps to create file if the file if does't not exist
                Boolean flag = f3.mkdir();
                Log.v("opendb", "mkdir flag: " + flag);

                destPath = destPath + "/AuditDb.sqlite";//It gives the destination path to copy the sqlite file from assert
                File f2 = new File(destPath);
                if (!f2.exists()) {
                    Log.v("opendb", "File Not Exist");
                    flag = f2.createNewFile();
                    Log.v("opendb", "create file flag: " + flag);
                }

                AssetManager assetManager = mycontext.getAssets();// getting the path of actual saved in asserts

                String[] files = null;

                files = assetManager.list("");// listing all files in assert 

                for (String filename : files) {// choosing the database file among other files
                    Log.i("opendb", filename);
                    InputStream in = null;  // to take stream of values from Source file
                    OutputStream out = null;    //  to write the value from source to destination file

                    if (filename.equals("HealthDb.sqlite")) {
                        in = assetManager.open(filename);
                        Log.i("opendb", filename + " opened Successfully");
                        out = new FileOutputStream(destPath);
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = in.read(buffer)) > 0) {
                            out.write(buffer, 0, length);
                        }
                        in.close();// terminating inputstream
                        out.close();// terminating outputstream
                    }
                }
            }


        } catch (FileNotFoundException e) {
            Log.v("opendb", "FileNotFoundexeption: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            Log.v("opendb", "ioexeption: " + e.getMessage());
            e.printStackTrace();
        }
        Log.v("opendb", "Success!!!!!!!!!!!!!!!!");

    }

    public SQLiteDatabase checkDB() { // this method helps to check whether the data base is exist or not 
        try {
            dbe = SQLiteDatabase.openDatabase(
                    "data/data/com.healthmonitor/databases/AuditDb.sqlite",
                    null, 0);
            Log.d("opendb", "EXIST");

        } catch (Exception e) {
            Log.d("opendb", e.getMessage());
        }
        return dbe;
    }

    public SQLiteDatabase createOrOpenDB(String dbName) { // this method helps to check whether the data base is exist or not 
        try {
            System.out.println("comming4");
            if(!dbName.equals("")){
            dbe = SQLiteDatabase.openDatabase(
                    "data/data/com.healthmonitor/databases/"+dbName+".sqlite",
                    null,0);// it opens the exist database 
            System.out.println("comming5");

            }

        } catch (Exception e) {
            System.out.println("comming44");
            Log.d("opendb", e.getMessage());
            dbe = SQLiteDatabase.openOrCreateDatabase(
                    "data/data/com.healthmonitor/databases/"+dbName+".sqlite",
                    null);// it creates the database if it does not exists
        }
        return dbe;
    }

}

数据库适配器类

public class DbAdapter {

    public static final String KEY_ID = "_id";
    public static final String KEY_COMP_ID = "compID";
    public static final String KEY_DBASE = "dbase";
    public static final String KEY_DTABLE = "dtable";
    public static final String KEY_DTFITELD = "dtfield";
    public static final String KEY_ACTION = "action";
    public static final String KEY_ORIGINATION = "origination";
    public static final String KEY_TERMINATION = "termination";
    public static final String KEY_INDEX = "fieldIndex";
    private static final String TAG = "DbAdapter";
    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "HealthDb.sqlite";
    private static final String FTS_AUDIT_TABLE = "audit_table";
    private static final int DATABASE_VERSION = 2;// Version of sqlite database

    private static Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
            mDb = cb.checkDB();
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");

        }
    }

    public DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public DbAdapter open() throws SQLException {

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.checkDB();
        return this;
    }

    public DbAdapter createOrOpenDb(String dbName) throws SQLException {
        //system.out.println("comming3");
        if (!dbName.equals("")) {
            DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
            mDb = cb.createOrOpenDB(dbName);
            //system.out.println("comming4");
            return this;
        }
        return null;
    }

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

    public void DatabaseAdd(String databaseName) {

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());
        //system.out.println("data is " + timeStamp);

        createOrOpenDb(databaseName);// creates the database with the specified
                                        // name

        open();
        ContentValues initialValues = new ContentValues();// Initializes the
                                                            // content value

        initialValues.put(KEY_DBASE, databaseName);

        initialValues.put(KEY_ACTION, "Database created");
        initialValues.put(KEY_ORIGINATION, timeStamp);

        long done = mDb.insert(FTS_AUDIT_TABLE, null, initialValues);
        //system.out.println("done " + done);

        String query = "UPDATE " + FTS_AUDIT_TABLE + " SET " + KEY_COMP_ID
                + "=(SELECT " + KEY_ID + " FROM " + FTS_AUDIT_TABLE + " WHERE "
                + KEY_ORIGINATION + " =" + timeStamp + ") WHERE "
                + KEY_ORIGINATION + " =" + timeStamp;
        mDb.execSQL(query);

        close();
    }

    public boolean DatabaseDelete(String databaseName) {

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());
        //system.out.println("time stamp in delete " + timeStamp);

        File file = new File("data/data/com.healthmonitor/databases/"
                + databaseName + ".sqlite");// selects the db file from the
                                            // system
        new File("data/data/com.healthmonitor/databases/" + databaseName
                + "-journal").delete();

        if (file.delete()) {
            open();

            String query2 = "UPDATE " + FTS_AUDIT_TABLE + " SET "
                    + KEY_TERMINATION + "='" + timeStamp + "' WHERE "
                    + KEY_DBASE + " = '" + databaseName + "' and "
                    + KEY_TERMINATION + " is null;";

            mDb.execSQL(query2);

            close();

            return true;

        }
        return false;
    }

    public boolean DatabaseExistOrNot(String databaseName) {

        File file = new File("data/data/com.healthmonitor/databases/"
                + databaseName + ".sqlite");
        return file.exists();
    }

    public boolean DatabaseEdit(String oldDatabaseName, String newDatabseNAme) {
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());

        File filefrom = new File("data/data/com.healthmonitor/databases/"
                + oldDatabaseName + ".sqlite");

        File fileto = new File("data/data/com.healthmonitor/databases/"
                + newDatabseNAme + ".sqlite");

        if (filefrom.renameTo(fileto)) {

            open();

            String query3 = "Select " + KEY_COMP_ID + "," + KEY_DTFITELD + ","
                    + KEY_INDEX + "," + KEY_TERMINATION + "," + KEY_DTABLE
                    + " from " + FTS_AUDIT_TABLE + " where " + KEY_DBASE
                    + "= '" + oldDatabaseName + "' and " + KEY_TERMINATION
                    + " is null";
            Cursor cursor1 = mDb.rawQuery(query3, null);

            ContentValues initialValues = new ContentValues();
            if (cursor1 != null) {
                cursor1.moveToFirst();

                do {
                    initialValues.put(KEY_COMP_ID, cursor1.getString(0));
                    initialValues.put(KEY_DBASE, newDatabseNAme);
                    initialValues.put(KEY_DTABLE, cursor1.getString(4));
                    initialValues.put(KEY_DTFITELD, cursor1.getString(1));
                    initialValues.put(KEY_INDEX, cursor1.getString(2));
                    initialValues.put(KEY_ACTION, "Database is renamed from"
                            + oldDatabaseName);
                    initialValues.put(KEY_ORIGINATION, timeStamp);
                    initialValues.put(KEY_TERMINATION, cursor1.getString(3));
                    long done1 = mDb.insert(FTS_AUDIT_TABLE, null,
                            initialValues);

                } while (cursor1.moveToNext());

            }

            String query4 = "UPDATE " + FTS_AUDIT_TABLE + " SET "
                    + KEY_TERMINATION + "='" + timeStamp + "' WHERE "
                    + KEY_DBASE + " = '" + oldDatabaseName + "'";

            mDb.execSQL(query4);

            close();

            return true;
        }
        return false;
    }

    public void TableAdd(String selectedDb, String Tablename) {

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);

        String query = "CREATE TABLE IF NOT EXISTS '" + Tablename
                + "' (_Id INTEGER PRIMARY KEY AUTOINCREMENT)";

        mDb.execSQL(query);

        mDb.close();
        open();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());
        ContentValues initialValues = new ContentValues();

        initialValues.put(KEY_DBASE, selectedDb);
        initialValues.put(KEY_DTABLE, Tablename);
        initialValues.put(KEY_ACTION, "Table Created");
        initialValues.put(KEY_ORIGINATION, timeStamp);
        long done = mDb.insert(FTS_AUDIT_TABLE, null, initialValues);

        String query1 = "UPDATE " + FTS_AUDIT_TABLE + " SET " + KEY_COMP_ID
                + "=(SELECT " + KEY_ID + " FROM " + FTS_AUDIT_TABLE + " WHERE "
                + KEY_ORIGINATION + " =" + timeStamp + ") WHERE "
                + KEY_ORIGINATION + " =" + timeStamp;
        mDb.execSQL(query1);

        AddField(selectedDb, Tablename, "_Id", "Text", "NO");
        AddField(selectedDb, Tablename, "Orgination", "Text", "NO");
        AddField(selectedDb, Tablename, "Termination", "Text", "NO");
        close();

    }

    public Cursor TableNames(String selectedDb) {
        if (!selectedDb.equals("")) {

            DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
            mDb = cb.createOrOpenDB(selectedDb);
            String query = "SELECT * FROM sqlite_master WHERE type='table'";
            Cursor cursor = mDb.rawQuery(query, null);
            if (cursor != null) {
                cursor.moveToFirst();
            }
            mDb.close();
            return cursor;
        }
        return null;

    }

    public boolean TableDelete(String selectedDb, String selectedTable) {

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);
        String query = "Drop table '" + selectedTable + "'";

        mDb.execSQL(query);

        mDb.close();

        open();

        String query2 = "UPDATE " + FTS_AUDIT_TABLE + " SET " + KEY_TERMINATION
                + "='" + timeStamp + "' WHERE " + KEY_DBASE + " = '"
                + selectedDb + "' and " + KEY_DTABLE + " ='" + selectedTable
                + "' and " + KEY_TERMINATION + " is null";
        mDb.execSQL(query2);

        close();
        return true;

    }

    public void TableEdit(String selectedDb, String selectedTable,
            String newTableName) {

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());

        try {
            String query = "ALTER TABLE '" + selectedTable + "' RENAME TO '"
                    + newTableName + "'";
            mDb.execSQL(query);

            mDb.close();
            open();

            String query3 = "Select " + KEY_COMP_ID + "," + KEY_DTFITELD + ","
                    + KEY_INDEX + "," + KEY_TERMINATION + " from "
                    + FTS_AUDIT_TABLE + " where " + KEY_DBASE + "= '"
                    + selectedDb + "' and " + KEY_DTABLE + "='" + selectedTable
                    + "' and " + KEY_TERMINATION + " is null";
            Cursor cursor1 = mDb.rawQuery(query3, null);

            ContentValues initialValues = new ContentValues();// Initializes 

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

                do {
                    initialValues.put(KEY_COMP_ID, cursor1.getString(0));
                    initialValues.put(KEY_DBASE, selectedDb);
                    initialValues.put(KEY_DTABLE, newTableName);
                    initialValues.put(KEY_DTFITELD, cursor1.getString(1));
                    initialValues.put(KEY_INDEX, cursor1.getString(2));
                    initialValues.put(KEY_ACTION, "Table is renamed from"
                            + selectedTable);
                    initialValues.put(KEY_ORIGINATION, timeStamp);
                    initialValues.put(KEY_TERMINATION, cursor1.getString(3));
                    long done1 = mDb.insert(FTS_AUDIT_TABLE, null,
                            initialValues);
                    //system.out.println("done " + done1);

                } while (cursor1.moveToNext());

            }

            String query4 = "UPDATE " + FTS_AUDIT_TABLE + " SET "
                    + KEY_TERMINATION + "='" + timeStamp + "' WHERE "
                    + KEY_DBASE + " = '" + selectedDb + "' and " + KEY_DTABLE
                    + " ='" + selectedTable + "' and " + KEY_TERMINATION
                    + " is null";
            //system.out.println("query4" + query4);

            mDb.execSQL(query4);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        close();
    }

    public Cursor TableView(String selectedDb, String selectedTable, int check) {

        Cursor cursor;

        if (!selectedTable.equals(FTS_AUDIT_TABLE)) {
            open();

            String query1 = "select  " + KEY_DTFITELD + " from "
                    + FTS_AUDIT_TABLE + " where " + KEY_DBASE + " = '"
                    + selectedDb + "' and " + KEY_DTABLE + " = '"
                    + selectedTable + "' and " + KEY_TERMINATION + " is null;";
            //system.out.println(query1);
            Cursor cursor1 = mDb.rawQuery(query1, null);
            String deletedField = "";
            try {
                if (cursor1 != null) {
                    cursor1.moveToFirst();

                    do {
                        if (cursor1.getString(cursor1
                                .getColumnIndex(DbAdapter.KEY_DTFITELD)) != null) {

                            deletedField = deletedField
                                    + cursor1
                                            .getString(cursor1
                                                    .getColumnIndex(DbAdapter.KEY_DTFITELD))
                                    + ",";
                        }

                    } while (cursor1.moveToNext());
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            //system.out.println("not removed fields" + deletedField);
            close();
            DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
            mDb = cb.createOrOpenDB(selectedDb);

            String query;
            if (check == 0) {
                query = "SELECT "
                        + deletedField.substring(0, deletedField.length() - 1)
                        + " FROM '" + selectedTable
                        + "' where Termination is null";
            } else {

                query = "SELECT "
                        + deletedField.substring(0, deletedField.length() - 1)
                        + " FROM '" + selectedTable + "'";
            }

            cursor = mDb.rawQuery(query, null);
            if (cursor != null) {
                cursor.moveToFirst();
            }
            mDb.close();
            return cursor;

        }

        else {
            if (check == 0) {
                DataBaseHelper cb = new DataBaseHelper(mCtx,
                        mCtx.getPackageName());
                mDb = cb.createOrOpenDB(selectedDb);
                String query = "SELECT * FROM '" + selectedTable + "' where "
                        + KEY_TERMINATION + " is null";

                cursor = mDb.rawQuery(query, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                }
                mDb.close();
                return cursor;
            } else {
                DataBaseHelper cb = new DataBaseHelper(mCtx,
                        mCtx.getPackageName());
                mDb = cb.createOrOpenDB(selectedDb);
                String query = "SELECT * FROM '" + selectedTable + "'";
                cursor = mDb.rawQuery(query, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                }
                mDb.close();
                return cursor;

            }
        }

    }

    public void DeleteRow(String selectedDb, String selectedTable, String rowid) {

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());

        String query2 = "UPDATE " + selectedTable + " SET " + "Termination = '"
                + timeStamp + "' where _Id =" + Integer.parseInt(rowid);

        mDb.execSQL(query2);
        mDb.close();

    }

    public boolean AddRow(String selectedDb, String selectedTable,
            String[] fieldvalue, Cursor cursor) {
        // TODO Auto-generated method stub

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());

        String columnname="Orgination";
        String values="'"+timeStamp+"'";

        for (int i = 3; i < cursor.getColumnCount(); i++) {

            fieldvalue[i]);

            columnname=columnname+","+cursor.getColumnName(i);
            values=values+",'"+fieldvalue[i]+"'";

        }

        String query="INSERT INTO "+selectedTable+" ("+columnname+") VALUES ("+values+")"; 

            try {
                mDb.execSQL(query);
                mDb.close();
                return true;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                mDb.close();
                return false;
            }                                                       
    }

    public boolean EditRow(String selectedDb, String selectedTable,
            String[] fieldvalue, Cursor cursor, String selectedRowId) {

        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);

        ContentValues initialValues = new ContentValues();
        for (int i = 3; i < cursor.getColumnCount(); i++) {

            initialValues.put(cursor.getColumnName(i), fieldvalue[i]);
        }

        long done = mDb.update(selectedTable, initialValues,
                cursor.getColumnName(0) + "=" + selectedRowId, null);

        mDb.close();
        if (done != -1)
            return true;

        return false;
    }

    public Cursor TableValues(String selectedDb, String selectedTable) {
        // TODO Auto-generated method stub
        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        mDb = cb.createOrOpenDB(selectedDb);

        String query = "PRAGMA table_info ('" + selectedTable + "')";

        Cursor cursor = mDb.rawQuery(query, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        mDb.close();
        return cursor;

    }

    public boolean AddField(String selectedDb, String selectedTable,
            String fieldName, String fieldType, String index) {

        try {
            DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());

        if (!fieldName.equals("_Id")) {
                mDb = cb.createOrOpenDB(selectedDb);
                String query = "ALTER TABLE '" + selectedTable
                        + "' ADD COLUMN '" + fieldName + "' '" + fieldType
                        + "';";

                mDb.execSQL(query);

                mDb.close();
            }
            open();

            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                    .format(Calendar.getInstance().getTime());
            //system.out.println("data is " + timeStamp);

            ContentValues initialValues = new ContentValues();// Initializes

            initialValues.put(KEY_DBASE, selectedDb);
            initialValues.put(KEY_DTABLE, selectedTable);
            initialValues.put(KEY_DTFITELD, fieldName);
            initialValues.put(KEY_ACTION, "field is created ");
            initialValues.put(KEY_ORIGINATION, timeStamp);
            initialValues.put(KEY_INDEX, index);

            long done = mDb.insert(FTS_AUDIT_TABLE, null, initialValues);
            //system.out.println("done " + done);

            String query2 = "UPDATE " + FTS_AUDIT_TABLE + " SET " + KEY_COMP_ID
                    + "=(SELECT " + KEY_ID + " FROM " + FTS_AUDIT_TABLE
                    + " WHERE " + KEY_ORIGINATION + " ='" + timeStamp
                    + "' ORDER BY " + KEY_ID + " DESC) WHERE "
                    + KEY_ORIGINATION + " ='" + timeStamp + "' and "
                    + KEY_DTFITELD + "='" + fieldName + "' ;";
            mDb.execSQL(query2);

            close();
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }

    public Cursor IndexValues(String selectedDb, String selectedTable) {
        // TODO Auto-generated method stub
        DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
        try {
            open();

            String query = "select " + KEY_DTFITELD + "," + KEY_INDEX
                    + " from " + FTS_AUDIT_TABLE + " where " + KEY_DBASE + "='"
                    + selectedDb + "' and " + KEY_DTABLE + " ='"
                    + selectedTable + "' and " + KEY_DTFITELD
                    + " not NULL and " + KEY_TERMINATION + " is null";
            //system.out.println(query);
            Cursor cursor = mDb.rawQuery(query, null);

            if (cursor != null) {
                cursor.moveToFirst();
            }

            return cursor;
        } catch (Exception e) {
            // TODO Auto-generated catch block

            e.printStackTrace();

        }
        close();
        return null;

    }

    public boolean DeleteField(String selectedDb, String selectedTable,
            String fieldName) {

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(Calendar.getInstance().getTime());
        //system.out.println("data is " + timeStamp);
        open();

        try {
            String query1 = "UPDATE " + FTS_AUDIT_TABLE + " SET "
                    + KEY_TERMINATION + "='" + timeStamp + "' where "
                    + KEY_DBASE + "='" + selectedDb + "' and " + KEY_DTABLE
                    + "='" + selectedTable + "' and " + KEY_DTFITELD + "='"
                    + fieldName + "' and " + KEY_TERMINATION + " is null;";
            //system.out.println(query1);

            mDb.execSQL(query1);
            mDb.close();


        } catch (SQLException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
            return false;
        }

        close();

        return true;

    }

    public String GetDeleteField(String selectedDb, String selectedTable) {

        open();

        String query1 = "select  " + KEY_DTFITELD + " from " + FTS_AUDIT_TABLE
                + " where " + KEY_DBASE + " = '" + selectedDb + "' and "
                + KEY_DTABLE + " = '" + selectedTable + "' and "
                + KEY_TERMINATION + " not null and " + KEY_ID + ">= (Select "
                + KEY_ID + " from " + FTS_AUDIT_TABLE + "  where " + KEY_DBASE
                + " = '" + selectedDb + "' and " + KEY_DTABLE + " = '"
                + selectedTable + "' and " + KEY_TERMINATION
                + " is null Order By " + KEY_ID + " desc );";
        //system.out.println(query1);

        Cursor cursor = mDb.rawQuery(query1, null);

        String deletedField = "";
        try {
            if (cursor != null) {
                cursor.moveToFirst();

                do {

                    deletedField = deletedField
                            + cursor.getString(cursor
                                    .getColumnIndex(DbAdapter.KEY_DTFITELD));

                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        close();

        //system.out.println("deleted fields" + deletedField);



        return deletedField;

    }

    public boolean EditField(String selectedDb, String selectedTable,
            String OldfieldName, String NewfieldName, String fieldType,
            String index) {

        try {

            DeleteField(selectedDb, selectedTable, OldfieldName);

            DataBaseHelper cb = new DataBaseHelper(mCtx, mCtx.getPackageName());
            mDb = cb.createOrOpenDB(selectedDb);

            String query = "ALTER TABLE '" + selectedTable + "' ADD COLUMN '"
                    + NewfieldName + "' '" + fieldType + "';";

            mDb.execSQL(query);

            mDb.close();

            open();

            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                    .format(Calendar.getInstance().getTime());

            ContentValues initialValues = new ContentValues();// Initializes

            initialValues.put(KEY_DBASE, selectedDb);
            initialValues.put(KEY_DTABLE, selectedTable);
            initialValues.put(KEY_DTFITELD, NewfieldName);
            initialValues.put(KEY_ACTION, "field is Edited from "
                    + OldfieldName);
            initialValues.put(KEY_ORIGINATION, timeStamp);
            initialValues.put(KEY_INDEX, index);

            long done = mDb.insert(FTS_AUDIT_TABLE, null, initialValues);
            //system.out.println("done " + done);

            String query2 = "UPDATE " + FTS_AUDIT_TABLE + " SET " + KEY_COMP_ID
                    + "=(SELECT " + KEY_COMP_ID + " FROM " + FTS_AUDIT_TABLE
                    + " WHERE " + KEY_DTFITELD + " ='" + OldfieldName
                    + "' ORDER BY " + KEY_ID + " DESC) WHERE "
                    + KEY_ORIGINATION + " ='" + timeStamp + "' and "
                    + KEY_DTFITELD + "='" + NewfieldName + "' ;";
            mDb.execSQL(query2);

            close();
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }

}

我正在使用“AddRow”方法来添加值

4

2 回答 2

0

通过手动创建 sqlite 数据库文件以及尝试指定数据库的路径,您做错了。你应该把它留给 SQLite 助手类来处理。也不建议像使用原始 sql 查询那样查询你的数据库,请改用 sqlitedatabase.query() 方法。如果你遇到麻烦你可以咨询我。请看一下这个类的例子:

public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;

// Database name
private static final String DATABASE_NAME = "stocktrader.db";

// Database tables
private static final String TABLE_SHARES = "Shares";
private static final String TABLE_ALERTS = "Alerts";
private static final String TABLE_TASKS = "Tasks";
private static final String TABLE_MESSAGES = "Messages";

// Shares table columns
private static final String KEY_NAME = "share_name";
private static final String KEY_PRICE = "share_price";
private static final String KEY_YESTERDAY = "share_yesterday_price";
private static final String KEY_CASH_CHANGE = "share_cash_change";
private static final String KEY_PERCENTAGE_CHANGE = "share_percentage_change";

// alerts table columns
private static final String KEY_SHARE_NAME = "share_name";
private static final String KEY_MIN_PRICE = "min_price";
private static final String KEY_MAX_PRICE = "max_price";
private static final String KEY_ACTION = "action";
private static final String KEY_USER = "user";

// tasks table columns
private static final String KEY_SHARENAME = "share_name";
private static final String KEY_TASK = "task";
private static final String KEY_MESSAGE = "message";
private static final String KEY_STATUS = "status";

// Messages table columns
private static final String KEY_HEADER = "title";
private static final String KEY_BODY = "message";
// private static final String KEY_DATE = "date";
private static final String KEY_ID = "message_id";
private static final String KEY_USER_ID = "user";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

String CREATE_TABLE_SHARES = "CREATE TABLE " + TABLE_SHARES + "("
        + KEY_NAME + " text primary key not null, " + KEY_PRICE
        + " double not null, " + KEY_YESTERDAY + " double, "
        + KEY_CASH_CHANGE + " double, " + KEY_PERCENTAGE_CHANGE
        + " double);";

String CREATE_TABLE_ALERTS = "CREATE TABLE " + TABLE_ALERTS + "("
        + KEY_SHARE_NAME + " text primary key not null," + KEY_MIN_PRICE
        + " double default null," + KEY_MAX_PRICE + " double default null,"
        + KEY_USER + " text not null," + KEY_ACTION + " int not null);";

String CREATE_TABLE_TASKS = "CREATE TABLE " + TABLE_TASKS + "("
        + KEY_SHARENAME + " text primary key not null," + KEY_TASK
        + " int not null," + KEY_MESSAGE + " text null," + KEY_STATUS
        + " int not null);";

String CREATE_TABLE_MESSAGES = "CREATE TABLE " + TABLE_MESSAGES + "("
        + KEY_ID + " integer primary key autoincrement," + KEY_HEADER
        + " text not null," + KEY_BODY + " text not null," + KEY_USER_ID
        + " text not null);";

// Creating tables
@Override
public void onCreate(SQLiteDatabase db) {
    try {
        db.execSQL(CREATE_TABLE_SHARES);
        db.execSQL(CREATE_TABLE_ALERTS);
        db.execSQL(CREATE_TABLE_TASKS);
        db.execSQL(CREATE_TABLE_MESSAGES);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(DatabaseHandler.class.getName(), "Upgrading from " + oldVersion
            + " to " + newVersion + ". All data will be lost.");

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARES);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALERTS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);

    // create tables again
    onCreate(db);
}

public void addShares(ArrayList<SharePrices> shares) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    String share_name;
    double share_price;
    double yesterday_price;
    for (int i = 0; i < shares.size(); i++) {
        try {
            Cursor cursor = null;
            share_name = shares.get(i).getName();
            share_price = Double.parseDouble(shares.get(i).getPrice());
            yesterday_price = Double.parseDouble(shares.get(i)
                    .getYesterdays());
            values.put(KEY_NAME, share_name);
            values.put(KEY_PRICE, share_price);
            values.put(KEY_YESTERDAY, yesterday_price);
            values.put(
                    KEY_CASH_CHANGE,
                    Math.round((share_price - yesterday_price) * 100.0) / 100.0);
            if (yesterday_price == 0) {
                values.put(KEY_PERCENTAGE_CHANGE, "100");
            } else {
                values.put(
                        KEY_PERCENTAGE_CHANGE,
                        Math.round((((share_price - yesterday_price) / yesterday_price) * 100) * 100.0) / 100.0);
            }
            cursor = database.query(TABLE_SHARES,
                    new String[] { KEY_NAME }, KEY_NAME + "=?",
                    new String[] { share_name }, null, null, null, null);

            if (cursor.getCount() == 1) {
                database.update(TABLE_SHARES, values, KEY_NAME + "=?",
                        new String[] { share_name });

                Log.i("db", "updated");
            } else {
                database.insert(TABLE_SHARES, null, values);

                Log.i("db", "inserted");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    database.close();
}

public void addToWatchList(String share_name, double max_price,
        double min_price, int action, String user) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    Cursor cursor = null;
    try {
        cursor = database.query(TABLE_ALERTS,
                new String[] { KEY_SHARE_NAME }, KEY_SHARE_NAME + "=? AND "
                        + KEY_USER + "=?",
                new String[] { share_name, user }, null, null, null, null);

        if (cursor.getCount() == 1) {
            if (max_price == 0.0) {
                values.put(KEY_SHARE_NAME, share_name);
                values.put(KEY_MIN_PRICE, min_price);
                values.put(KEY_ACTION, action);
                values.put(KEY_USER, user);
                database.update(TABLE_ALERTS, values, KEY_SHARE_NAME
                        + "=? AND " + KEY_USER + "=?", new String[] {
                        share_name, user });
            } else if (min_price == 0.0) {
                values.put(KEY_SHARE_NAME, share_name);
                values.put(KEY_MAX_PRICE, max_price);
                values.put(KEY_ACTION, action);
                values.put(KEY_USER, user);
                database.update(TABLE_ALERTS, values, KEY_SHARE_NAME
                        + "=? AND " + KEY_USER + "=?", new String[] {
                        share_name, user });
            }

            else {
                values.put(KEY_SHARE_NAME, share_name);
                values.put(KEY_MAX_PRICE, max_price);
                values.put(KEY_MIN_PRICE, min_price);
                values.put(KEY_ACTION, action);
                values.put(KEY_USER, user);
                database.insert(TABLE_ALERTS, null, values);
                database.update(TABLE_ALERTS, values, KEY_SHARE_NAME
                        + "=? AND " + KEY_USER + "=?", new String[] {
                        share_name, user });
            }
        } else {
            if (max_price == 0.0) {
                values.put(KEY_SHARE_NAME, share_name);
                values.put(KEY_MIN_PRICE, min_price);
                values.put(KEY_ACTION, action);
                values.put(KEY_USER, user);
                database.insert(TABLE_ALERTS, null, values);
            } else if (min_price == 0.0) {
                values.put(KEY_SHARE_NAME, share_name);
                values.put(KEY_MAX_PRICE, max_price);
                values.put(KEY_ACTION, action);
                values.put(KEY_USER, user);
                database.insert(TABLE_ALERTS, null, values);
            }

            else {
                values.put(KEY_SHARE_NAME, share_name);
                values.put(KEY_MAX_PRICE, max_price);
                values.put(KEY_MIN_PRICE, min_price);
                values.put(KEY_ACTION, action);
                values.put(KEY_USER, user);
                database.insert(TABLE_ALERTS, null, values);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    database.close();
}

public void addMessage(String message, String header, String user) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_HEADER, header);
    values.put(KEY_BODY, message);
    values.put(KEY_USER_ID, user);
    try {
        database.insert(TABLE_MESSAGES, null, values);
    } catch (Exception e) {
        e.printStackTrace();
    }
    database.close();
}

public Cursor getMessageHeaders(String user) {
    SQLiteDatabase database = this.getReadableDatabase();
    Cursor cursor = null;
    try {
        cursor = database.query(TABLE_MESSAGES, null, KEY_USER_ID + "=?",
                new String[] { user }, null, null, null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cursor;
}


public void deleteMessage(String message_id) {
    SQLiteDatabase database = this.getWritableDatabase();
    try {
        database.delete(TABLE_MESSAGES, KEY_ID + "=?",
                new String[] { message_id });
    } catch (Exception e) {
        e.printStackTrace();
    }
    database.close();
}

}

于 2013-10-09T06:13:13.277 回答
0

看起来您可能会遇到权限错误或路径错误。没有足够的信息来确定实际问题是什么。但我很惊讶你手动创建你的 sqlite 文件。Android 提供的 Sqlite 数据库几乎就像一个“服务”,您不必处理管理文件的复杂性。

查看本教程: http ://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

SqliteOpenHelper 应该是您所需要的,除非您尝试执行 SqliteOpenHelper 不支持的操作(这似乎不是这种情况),否则您不应该访问 db 文件。

您可以为您需要的每个 Sqlite 数据库创建一个专门的 SqliteOpenHelper 版本,或者您可以尝试创建一个管理所有数据库的单个版本(尽管它会更复杂且不推荐)。

编辑:哦,如果您要安装预填充的 sqlite 数据库,请参阅此线程: https ://stackoverflow.com/a/620086/2848773

于 2013-10-09T05:40:31.570 回答