Search code examples
androidactiveandroid

Error inserting Id=null when using ActiveAndriod ORM


Thanks for giving some of your precious time on it.

I am using ActiveAndroid ORM for my android project.I created Application class where I initialized the ActiveAndroid.I also created POJO class that extends Model from ActiveAndroid.

And in Manifiest within application tag I used meta as

<meta-data
            android:name="AA_DB_NAME"
            android:value="myFhn.db" />
        <meta-data
            android:name="AA_DB_VERSION"
            android:value="3" />

But while saving the object I am unable to save it. I dont know whats goin own some time it saves and some time it doesnot.

when I call this clearApplicationData method I got the above problems.

  public static void clearApplicationData(final Context context) {
        File cache = context.getCacheDir();
        File appDir = new File(cache.getParent());
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                File f = new File(appDir, s);
                if (deleteDir(f)) {
                    AppLog.i("Util", String.format("DELETED::", f.getAbsolutePath()));
                }
            }
        }
        context.getSharedPreferences(context.getPackageName(), context.MODE_PRIVATE).edit().clear();

    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                AppLog.i("Util", "DELETING:: " + aChildren);
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        assert dir != null;
        return dir.delete();
    }

    public static void restartApplication(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        int pendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(context, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

This is my Application class

public class FHNapplication extends com.activeandroid.app.Application {

    public static final String TAG = FHNapplication.class.getSimpleName();


    private static FHNapplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        try {
            ActiveAndroid.initialize(this);
            Log.i(TAG,"initialized");
        } catch (Exception e) {
            e.printStackTrace();
        }
        MultiDex.install(getBaseContext());
        Fabric.with(this, new Crashlytics());

    }

    public static synchronized FHNapplication getInstance() {
        return mInstance;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ActiveAndroid.dispose();
    }
}

This is my LOGIN POJO class

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Table(name = "User")
public class LoginData extends Model {

    @Column(name = "access_token")
    @JsonProperty("accessToken")
    private String accessToken;
    @Column(name = "full_name")
    @JsonProperty("fullname")
    private String fullname;
    @Column(name = "fhn_id")
    @JsonProperty("fhnId")
    private String fhnId;
    @Column(name = "imageUrl")
    @JsonProperty("image")
    private String imageUrl;

    public LoginData() {
        super();
    }


    public static LoginData getUserData() {
        return new Select().from(LoginData.class).executeSingle();
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getFhnId() {
        return fhnId;
    }

    public void setFhnId(String fhnId) {
        this.fhnId = fhnId;
    }
}

And this is how I tried to save the object

LoginData loginData = event.getLoginResponse().getData();
loginData.save();

while logging in I got this error

03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1) Path : / rc : 0 st_mode : 40755 st_uid : 0 st_gid : 0 Type:dir
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1) Path : /data/ rc : 0 st_mode : 40771 st_uid : 1000 st_gid : 1000 Type:dir
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1) Path : /data/data/ rc : 0 st_mode : 40771 st_uid : 1000 st_gid : 1000 Type:dir
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1) Path : /data/data/com.bidhee.familyhealthnepal/ rc : 0 st_mode : 40751 st_uid : 10260 st_gid : 10260 Type:dir
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1) Path : /data/data/com.bidhee.familyhealthnepal/databases/ rc : -1 st_mode : 0 st_uid : 0 st_gid : 0 Type:file
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1) Path : /data/data/com.bidhee.familyhealthnepal/databases/myFhn.db rc : -1 st_mode : 0 st_uid : 0 st_gid : 0 Type:file
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1802) os_unix.c:32353: (2) stat(/data/data/com.bidhee.familyhealthnepal/databases/myFhn.db) - 
03-18 14:10:01.793 16981-16981/com.bidhee.familyhealthnepal E/SQLiteLog: (1802) statement aborts at 29: [INSERT INTO User(Id,fhn_id,imageUrl,access_token,full_name) VALUES (?,?,?,?,?)] 
03-18 14:10:01.813 16981-16981/com.bidhee.familyhealthnepal E/SQLiteDatabase: Error inserting Id=null fhn_id=FHN-2015-3306 imageUrl=http://familyhealthnepal.com/uploads/members/images (3).jpg access_token=XHy4rHWR07ZivAZSeL5HLYWd full_name=Santosh Kumar Poudel
                                                                              android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 1802)
                                                                                  at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
                                                                                  at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:972)
                                                                                  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:1603)
                                                                                  at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1473)
                                                                                  at com.activeandroid.Model.save(Model.java:155)
                                                                                  at com.bidhee.familyhealthnepal.activity.LoginActivity.LoginResultEvent(LoginActivity.java:318)
                                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                  at com.squareup.otto.EventHandler.handleEvent(EventHandler.java:89)
                                                                                  at com.squareup.otto.Bus.dispatch(Bus.java:385)
                                                                                  at com.squareup.otto.Bus.dispatchQueuedEvents(Bus.java:368)
                                                                                  at com.squareup.otto.Bus.post(Bus.java:337)
                                                                                  at com.bidhee.familyhealthnepal.bus.EventBus.post(EventBus.java:44)
                                                                                  at com.bidhee.familyhealthnepal.controller.LoginPostTask$1.onResponse(LoginPostTask.java:32)
                                                                                  at retrofit.ExecutorCallAdapterFactory$ExecutorCallback$1.run(ExecutorCallAdapterFactory.java:86)
                                                                                  at android.os.Handler.handleCallback(Handler.java:733)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:146)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                  at dalvik.system.NativeStart.main(Native Method)

Solution

  • Calling the clearApplicationData(...) method deletes the database file from your application install folder, so later on you are trying to save/insert a record in a non-existing database and you get the errors you see in your logcat.

    So either do not delete the myFhn.db file when calling clearApplicationData(...) or recreate your database right after clearApplicationData(...) completes.

    EDIT: For example you could exclude your db file from deletion by changing deleteDir(File dir) method to:

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                AppLog.i("Util", "DELETING:: " + aChildren);
                if(!"myFhn.db".equals(aChildren.getName()) {
                    boolean success = deleteDir(new File(dir, aChildren));
                    if (!success) {
                        return false;
                    }
                }
            }
        }
        assert dir != null;
        return true; //dir.delete(); ->cannot delete dir since it contains the database file
    }