SQLite插入返回-1。删除包含数据库的文件夹后

时间:2019-02-23 04:06:17

标签: android sqlite android-fragments

以编程方式删除包含Database的文件夹后,下次调用Insert时,返回-1。我认为解决方案是通过调用数据库构造函数来重新创建数据库。但是我不知道如何在Fragment中进行操作。

数据库类:

public class SQliteHelperClass  extends SQLiteOpenHelper {
    public static final String Dabase_name= "UserRecord.db";
    public static final String Table_name= "RTable";
    public static final String col_0= "Id";
    public static final String col_1= "KM";
    public static final String col_2= "MDATE";
    public static final String col_3= "MTIME";
    public static final String col_4= "MDIFFER";


    public SQliteHelperClass(Context context) {
        super(context, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                + File.separator+"MyCarData"
                + File.separator +  Dabase_name, null, 1);

    }

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+ Table_name +"(Id INTEGER PRIMARY KEY AUTOINCREMENT, KM INTEGER, MDATE TEXT, MTIME TEXT , MDIFFER INTEGER) ");

}

public boolean insertData(KmDataModel kmDataModel) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(col_0,kmDataModel.getId());
    contentValues.put(col_1,kmDataModel.getKm());
    contentValues.put(col_2,kmDataModel.getDate());
    contentValues.put(col_3,kmDataModel.getTime());
    contentValues.put(col_4,kmDataModel.getDffKm());
    long result =db.insert(Table_name,null,contentValues);
    if(result == -1){
        return false;
    }else{
        return true;
    }
}

}

删除需要删除特定文件夹包含内容的删除方法

public void DeleteDataFolder(){
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
        + File.separator+"MyCarData"
        + File.separator);
if (dir.isDirectory())
{
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++)
    {

        Log.e("File_List",children[i]);
        new File(dir, children[i]).delete();
    }
}
}

请注意,如果我关闭应用程序并再次启动它,则数据库工作正常,因此我正在调用强制关闭应用程序的方法,但我不想关闭该应用程序。

1 个答案:

答案 0 :(得分:0)

您认为您需要重新创建/创建数据库助手的另一个实例是正确的。

因此刷新现有实例,例如date month value pmonth duration pduration newduration newpduration 0 2013-04-01 1 1 1 30 10 30.0 10.0 1 2013-04-01 1 1 1 15 20 15.0 20.0 2 2013-04-01 3 NaN 2 20 30 NaN NaN 3 2013-04-02 3 NaN 5 15 40 NaN NaN 4 2013-04-02 5 NaN 5 30 50 NaN NaN

  • 上下文必须是有效上下文

如果不这样做,您将在日志中获得以下内容:-

myInstanceOfDBHelper = new SQliteHelperClass(context)

您可能想知道删除后如何获得重复数据,可能是旧连接允许访问缓存的数据

以下代码用于上述操作:-

  • 您的 SQliteHelperClass (略作修改以输出插入尝试号)
  • 您的 KmDataModel 类的近似值,并且
  • 调用活动(易于编码)

活动代码为:-

2019-02-23 16:15:32.049 31038-31038/abc.so54838140sqlitealtfilelocation D/DBINSERT: Attempt # 1 at inserting into DB
2019-02-23 16:15:32.070 31038-31038/abc.so54838140sqlitealtfilelocation E/File_List: UserRecord.db
2019-02-23 16:15:32.070 31038-31038/abc.so54838140sqlitealtfilelocation E/File_List: UserRecord.db-wal
2019-02-23 16:15:32.071 31038-31038/abc.so54838140sqlitealtfilelocation E/File_List: UserRecord.db-shm
2019-02-23 16:15:32.071 31038-31038/abc.so54838140sqlitealtfilelocation D/DBINSERT: Attempt # 2 at inserting into DB
2019-02-23 16:15:32.074 31038-31038/abc.so54838140sqlitealtfilelocation E/SQLiteDatabase: Error inserting MDIFFER=30 KM=100 Id=1 MTIME=10:30 MDATE=2019-01-01
    android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: RTable.Id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
        at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
        at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
        at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
        at abc.so54838140sqlitealtfilelocation.SQliteHelperClass.insertData(SQliteHelperClass.java:48)
        at abc.so54838140sqlitealtfilelocation.MainActivity.onCreate(MainActivity.java:30)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
  • 带有注释行的注释未注释上述作品。 =因此,您要做的就是在片段中应用以上内容,这需要获取合适的上下文。如果您在获取上下文时遇到困难,那么Using context in a fragment 可能会有所帮助。

重新实例化后,运行后的日志为:-

public class MainActivity extends AppCompatActivity {

    SQliteHelperClass mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Build.VERSION.SDK_INT >= 23) {
            ExternalStoragePermissions.verifyStoragePermissions(this);
        }

        mDBHlpr = new SQliteHelperClass(this); //<<<<<<<<<< original instantiation
        KmDataModel k = new KmDataModel();
        k.setId(1);
        k.setKm(100);
        k.setDate("2019-01-01");
        k.setTime("10:30");
        k.setDffKm(30);
        mDBHlpr.insertData(k,1);
        mDBHlpr.DeleteDataFolder();
        // If not commeneted out line below will re-instantiate the DB helper
        //mDBHlpr = new SQliteHelperClass(this); //<<<<<<<<<< COMMENTED OUT TO FAIL
        mDBHlpr.insertData(k,2);
    }
}