Browse Source

Access to Uploads table through ContentResolver instead of direct access as DB

David A. Velasco 9 years ago
parent
commit
41f1924bb6

+ 78 - 97
src/com/owncloud/android/db/UploadDbHandler.java → src/com/owncloud/android/datamodel/UploadsStorageManager.java

@@ -2,6 +2,7 @@
  *   ownCloud Android client application
  *
  *   @author LukeOwncloud
+ *   @author David A. Velasco
  *   Copyright (C) 2015 ownCloud Inc.
  *
  *   This program is free software: you can redistribute it and/or modify
@@ -17,17 +18,17 @@
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */
-package com.owncloud.android.db;
+package com.owncloud.android.datamodel;
 
 import java.util.Observable;
 
+import android.content.ContentResolver;
 import android.content.ContentValues;
-import android.content.Context;
 import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteOpenHelper;
+import android.net.Uri;
 
-import com.owncloud.android.MainApp;
+import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
+import com.owncloud.android.db.UploadDbObject;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 import com.owncloud.android.lib.common.utils.Log_OC;
 
@@ -35,14 +36,11 @@ import com.owncloud.android.lib.common.utils.Log_OC;
  * Database helper for storing list of files to be uploaded, including status
  * information for each file.
  */
-public class UploadDbHandler extends Observable {
-    private SQLiteDatabase mDB;
-    private OpenerHelper mHelper;
-    private final String mDatabaseName;
-    private final int mDatabaseVersion = 4;
+public class UploadsStorageManager extends Observable {
 
-    static private final String TAG = UploadDbHandler.class.getSimpleName();
-    static private final String TABLE_UPLOAD = "list_of_uploads";
+    private ContentResolver mContentResolver;
+
+    static private final String TAG = UploadsStorageManager.class.getSimpleName();
 
     public enum UploadStatus {
         /**
@@ -84,53 +82,11 @@ public class UploadDbHandler extends Observable {
         }
     };
 
-    private UploadDbHandler(Context context) {
-        mDatabaseName = MainApp.getDBName();
-        mHelper = new OpenerHelper(context);
-    }
-
-    private static UploadDbHandler me = null;
-
-    static public UploadDbHandler getInstance(Context context) {
-        if (me == null) {
-            me = new UploadDbHandler(context);
-        }
-        return me;
-    }
-
-    public void close() {
-        getDB().close();
-        setDB(null);
-        me = null;
-    }
-
-    private class OpenerHelper extends SQLiteOpenHelper {
-        public OpenerHelper(Context context) {
-            super(context, mDatabaseName, null, mDatabaseVersion);
-        }
-
-        @Override
-        public void onCreate(SQLiteDatabase db) {
-            // PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a
-            // bug in some early versions, this is not the case in SQLite.
-            db.execSQL("CREATE TABLE " + TABLE_UPLOAD + " (" + " path TEXT PRIMARY KEY NOT NULL UNIQUE,"
-                    + " uploadStatus INTEGER NOT NULL, uploadObject TEXT NOT NULL);");
-            // uploadStatus is used to easy filtering, it has precedence over
-            // uploadObject.getUploadStatus()
-        }
-
-        @Override
-        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-            if (newVersion == 4) {
-                db.execSQL("DROP TABLE IF EXISTS " + "instant_upload" + ";"); // drop
-                                                                              // old
-                                                                              // db
-                                                                              // (name)
-                db.execSQL("DROP TABLE IF EXISTS " + TABLE_UPLOAD + ";");
-                onCreate(db);
-            }
-
+    public UploadsStorageManager(ContentResolver contentResolver) {
+        if (contentResolver == null) {
+            throw new IllegalArgumentException("Cannot create an instance with a NULL contentResolver");
         }
+        mContentResolver = contentResolver;
     }
 
     /**
@@ -140,17 +96,17 @@ public class UploadDbHandler extends Observable {
      * @return true on success.
      */
     public boolean storeUpload(UploadDbObject uploadObject) {
-        Log_OC.e(TAG, "Inserting "+uploadObject.getLocalPath()+" with uploadStatus="+uploadObject.getUploadStatus());
+        Log_OC.e(TAG, "Inserting " + uploadObject.getLocalPath() + " with uploadStatus=" + uploadObject.getUploadStatus());
         
         ContentValues cv = new ContentValues();
-        cv.put("path", uploadObject.getLocalPath());
-        cv.put("uploadStatus", uploadObject.getUploadStatus().value);
-        cv.put("uploadObject", uploadObject.toString());
+        cv.put(ProviderTableMeta.UPLOADS_PATH, uploadObject.getLocalPath());
+        cv.put(ProviderTableMeta.UPLOADS_STATUS, uploadObject.getUploadStatus().value);
+        // TODO - CRITICAL cv.put("uploadObject", uploadObject.toString());
 
-        long result = getDB().insert(TABLE_UPLOAD, null, cv);
+        Uri result = getDB().insert(ProviderTableMeta.CONTENT_URI_UPLOADS, cv);
         
         Log_OC.d(TAG, "storeUpload returns with: " + result + " for file: " + uploadObject.getLocalPath());
-        if (result == -1) {
+        if (result == null) {
             Log_OC.e(TAG, "Failed to insert item " + uploadObject.getLocalPath() + " into upload db.");
             return false;
         } else {
@@ -188,11 +144,15 @@ public class UploadDbHandler extends Observable {
             uploadObjectString = uploadObject.toString();
             // store update upload object to db
             ContentValues cv = new ContentValues();
-            cv.put("uploadStatus", status.value);
-            cv.put("uploadObject", uploadObjectString);
-            
-            
-            int r = getDB().update(TABLE_UPLOAD, cv, "path=?", new String[] { path });
+            cv.put(ProviderTableMeta.UPLOADS_STATUS, status.value);
+            // TODO - CRITICAL cv.put("uploadObject", uploadObjectString);
+
+            int r = getDB().update(
+                    ProviderTableMeta.CONTENT_URI_UPLOADS,
+                    cv,
+                    ProviderTableMeta.UPLOADS_PATH + "=?",
+                    new String[] {path}
+            );
             
             if (r == 1) {
                 notifyObserversNow();
@@ -212,10 +172,15 @@ public class UploadDbHandler extends Observable {
      * @return 1 if file status was updated, else 0.
      */
     public int updateUploadStatus(String filepath, UploadStatus status, RemoteOperationResult result) {
+        //Log_OC.e(TAG, "Updating "+filepath+" with uploadStatus="+status +" and result="+result);
         
-//        Log_OC.e(TAG, "Updating "+filepath+" with uploadStatus="+status +" and result="+result);
-        
-        Cursor c = getDB().query(TABLE_UPLOAD, null, "path=?", new String[] { filepath }, null, null, null);
+        Cursor c = getDB().query(
+                ProviderTableMeta.CONTENT_URI_UPLOADS,
+                null,
+                ProviderTableMeta.UPLOADS_PATH + "=?",
+                new String[] { filepath },
+                null
+        );
 
         if (c.getCount() != 1) {
             Log_OC.e(TAG, c.getCount() + " items for path=" + filepath
@@ -243,8 +208,12 @@ public class UploadDbHandler extends Observable {
      * @return true when one or more upload entries were removed
      */
     public int removeUpload(String localPath) {
-        int result = getDB().delete(TABLE_UPLOAD, "path = ?", new String[] { localPath });
-        Log_OC.d(TABLE_UPLOAD, "delete returns with: " + result + " for file: " + localPath);
+        int result = getDB().delete(
+                ProviderTableMeta.CONTENT_URI_UPLOADS,
+                ProviderTableMeta.UPLOADS_PATH,
+                new String[] { localPath }
+        );
+        Log_OC.d(TAG, "delete returns with: " + result + " for file: " + localPath);
         if(result > 0) {
             notifyObserversNow();
         }
@@ -261,7 +230,13 @@ public class UploadDbHandler extends Observable {
 
 
     private UploadDbObject[] getUploads(String selection, String[] selectionArgs) {
-        Cursor c = getDB().query(TABLE_UPLOAD, null, selection, selectionArgs, null, null, null);
+        Cursor c = getDB().query(
+                ProviderTableMeta.CONTENT_URI_UPLOADS,
+                null,
+                selection,
+                selectionArgs,
+                null
+        );
         UploadDbObject[] list = new UploadDbObject[c.getCount()];
         if (c.moveToFirst()) {
             do {
@@ -321,23 +296,20 @@ public class UploadDbHandler extends Observable {
         return getUploads("uploadStatus==" + UploadStatus.UPLOAD_SUCCEEDED.value, null);
     }
 
-    private SQLiteDatabase getDB() {
-        if (mDB == null) {
-            mDB = mHelper.getWritableDatabase();
-        }
-        return mDB;
-    }
-
-    private void setDB(SQLiteDatabase mDB) {
-        this.mDB = mDB;
+    private ContentResolver getDB() {
+        return mContentResolver;
     }
 
     public long clearFailedUploads() {
-        String[] where = new String[2];
-        where[0] = String.valueOf(UploadStatus.UPLOAD_CANCELLED.value);
-        where[1] = String.valueOf(UploadStatus.UPLOAD_FAILED_GIVE_UP.value);
-        long result = getDB().delete(TABLE_UPLOAD, "uploadStatus = ? OR uploadStatus = ?", where);
-        Log_OC.d(TABLE_UPLOAD, "delete all failed uploads");
+        String[] whereArgs = new String[2];
+        whereArgs[0] = String.valueOf(UploadStatus.UPLOAD_CANCELLED.value);
+        whereArgs[1] = String.valueOf(UploadStatus.UPLOAD_FAILED_GIVE_UP.value);
+        long result = getDB().delete(
+                ProviderTableMeta.CONTENT_URI_UPLOADS,
+                ProviderTableMeta.UPLOADS_STATUS + "=? OR " + ProviderTableMeta.UPLOADS_STATUS + "=?",
+                whereArgs
+        );
+        Log_OC.d(TAG, "delete all failed uploads");
         if (result > 0) {
             notifyObserversNow();
         }
@@ -345,10 +317,14 @@ public class UploadDbHandler extends Observable {
     }
 
     public long clearFinishedUploads() {
-        String[] where = new String[1];
-        where[0] = String.valueOf(UploadStatus.UPLOAD_SUCCEEDED.value);
-        long result = getDB().delete(TABLE_UPLOAD, "uploadStatus = ?", where);
-        Log_OC.d(TABLE_UPLOAD, "delete all finished uploads");
+        String[] whereArgs = new String[1];
+        whereArgs[0] = String.valueOf(UploadStatus.UPLOAD_SUCCEEDED.value);
+        long result = getDB().delete(
+                ProviderTableMeta.CONTENT_URI_UPLOADS,
+                ProviderTableMeta.UPLOADS_STATUS + "=? ",
+                whereArgs
+        );
+        Log_OC.d(TAG, "delete all finished uploads");
         if (result > 0) {
             notifyObserversNow();
         }
@@ -356,10 +332,15 @@ public class UploadDbHandler extends Observable {
     }
     
     public void setAllCurrentToUploadLater() {
-        
-        Cursor c = getDB().query(TABLE_UPLOAD, null, "uploadStatus==" + UploadStatus.UPLOAD_IN_PROGRESS.value,
-                null, null, null, null);
-        
+        Cursor c = getDB().query(
+                ProviderTableMeta.CONTENT_URI_UPLOADS,
+                null,
+                ProviderTableMeta.UPLOADS_STATUS + "=? ",
+                new String[]{
+                        Integer.toString(UploadStatus.UPLOAD_IN_PROGRESS.value)
+                },
+                null
+        );
         updateUploadInternal(c, UploadStatus.UPLOAD_LATER, null);
     }
 

+ 3 - 2
src/com/owncloud/android/db/UploadDbObject.java

@@ -34,14 +34,15 @@ import android.util.Base64;
 
 import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.db.UploadDbHandler.UploadStatus;
+import com.owncloud.android.datamodel.UploadsStorageManager;
+import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
 import com.owncloud.android.files.services.FileUploadService.LocalBehaviour;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 import com.owncloud.android.lib.common.utils.Log_OC;
 
 /**
  * Stores all information in order to start upload operations. PersistentUploadObject can
- * be stored persistently by {@link UploadDbHandler}.
+ * be stored persistently by {@link UploadsStorageManager}.
  * 
  */
 public class UploadDbObject implements Serializable {

+ 45 - 28
src/com/owncloud/android/files/services/FileUploadService.java

@@ -58,8 +58,8 @@ import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.db.UploadDbHandler;
-import com.owncloud.android.db.UploadDbHandler.UploadStatus;
+import com.owncloud.android.datamodel.UploadsStorageManager;
+import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
 import com.owncloud.android.db.UploadDbObject;
 import com.owncloud.android.lib.common.OwnCloudAccount;
 import com.owncloud.android.lib.common.OwnCloudClient;
@@ -90,7 +90,7 @@ import com.owncloud.android.utils.UriUtils;
 
 /**
  * Service for uploading files. Invoke using context.startService(...). Files to
- * be uploaded are stored persistently using {@link UploadDbHandler}.
+ * be uploaded are stored persistently using {@link UploadsStorageManager}.
  * 
  * On next invocation of {@link FileUploadService} uploaded files which
  * previously failed will be uploaded again until either upload succeeded or a
@@ -213,7 +213,7 @@ public class FileUploadService extends Service implements OnDatatransferProgress
     private Account mLastAccount = null;
     private FileDataStorageManager mStorageManager;
     //since there can be only one instance of an Android service, there also just one db connection.
-    private UploadDbHandler mDb = null;
+    private UploadsStorageManager mUploadsStorageManager = null;
     
     private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
     private final AtomicBoolean mCancellationPossible = new AtomicBoolean(false);
@@ -280,11 +280,10 @@ public class FileUploadService extends Service implements OnDatatransferProgress
         Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - onCreate");
         mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
         mBinder = new FileUploaderBinder();
-        mDb = UploadDbHandler.getInstance(this);
-//        mDb.recreateDb(); //for testing only
-        
+        mUploadsStorageManager = new UploadsStorageManager(getContentResolver());
+
         //when this service starts there is no upload in progress. if db says so, app probably crashed before.
-        mDb.setAllCurrentToUploadLater();
+        mUploadsStorageManager.setAllCurrentToUploadLater();
         
         HandlerThread thread = new HandlerThread("FileUploadService-Requester");
         thread.start();
@@ -351,8 +350,8 @@ public class FileUploadService extends Service implements OnDatatransferProgress
      * 
      * First, onHandleIntent() stores all information associated with the upload
      * in a {@link UploadDbObject} which is stored persistently using
-     * {@link UploadDbHandler}. Then, the oldest, pending upload from
-     * {@link UploadDbHandler} is taken and upload is started.
+     * {@link UploadsStorageManager}. Then, the oldest, pending upload from
+     * {@link UploadsStorageManager} is taken and upload is started.
      * @param intentStartId 
      */
 
@@ -365,7 +364,7 @@ public class FileUploadService extends Service implements OnDatatransferProgress
             // retry of pending upload was requested. 
             // ==> First check persistent uploads, then perform upload.
             int countAddedEntries = 0;
-            UploadDbObject[] list = mDb.getPendingUploads();
+            UploadDbObject[] list = mUploadsStorageManager.getPendingUploads();
             for (UploadDbObject uploadDbObject : list) {
                 Log_OC.d(TAG, "Retrieved from DB: " + uploadDbObject.toFormattedString());
                 
@@ -381,9 +380,9 @@ public class FileUploadService extends Service implements OnDatatransferProgress
             Log_OC.d(TAG, "added " + countAddedEntries
                     + " entrie(s) to mPendingUploads (this should be 0 except for the first time).");
             // null intent is received when charging or wifi state changes.
-            // fake a mDb change event, so that GUI can update the reason for
+            // fake a mUploadsStorageManager change event, so that GUI can update the reason for
             // LATER status of uploads.
-            mDb.notifyObserversNow();
+            mUploadsStorageManager.notifyObserversNow();
         } else {
             Log_OC.d(TAG, "Receive upload intent.");
             UploadQuantity uploadType = (UploadQuantity) intent.getSerializableExtra(KEY_UPLOAD_TYPE);
@@ -481,11 +480,11 @@ public class FileUploadService extends Service implements OnDatatransferProgress
                     // however, it can happened that the user uploaded the same
                     // file before in which case there is an old db entry.
                     // delete that to be sure we have the latest one.
-                    if(mDb.removeUpload(uploadObject.getLocalPath())>0) {
+                    if(mUploadsStorageManager.removeUpload(uploadObject.getLocalPath())>0) {
                         Log_OC.w(TAG, "There was an old DB entry " + uploadObject.getLocalPath()
                                 + " which had to be removed in order to add new one.");
                     }
-                    boolean success = mDb.storeUpload(uploadObject);
+                    boolean success = mUploadsStorageManager.storeUpload(uploadObject);
                     if(!success) {
                         Log_OC.e(TAG, "Could not add upload " + uploadObject.getLocalPath()
                                 + " to database. This should not happen.");
@@ -511,7 +510,7 @@ public class FileUploadService extends Service implements OnDatatransferProgress
             UploadDbObject uploadDbObject = mPendingUploads.get(remotePath);
             uploadDbObject.setUploadStatus(UploadStatus.UPLOAD_LATER);
             uploadDbObject.setLastResult(null);
-            mDb.updateUploadStatus(uploadDbObject);
+            mUploadsStorageManager.updateUploadStatus(uploadDbObject);
 
             Log_OC.d(TAG, "Start uploading " + remotePath);
         } else {
@@ -557,7 +556,7 @@ public class FileUploadService extends Service implements OnDatatransferProgress
     }
 
     /**
-     * Tries uploading uploadDbObject, creates notifications, and updates mDb.
+     * Tries uploading uploadDbObject, creates notifications, and updates mUploadsStorageManager.
      */
     public class UploadTask implements Runnable {
         UploadDbObject uploadDbObject;
@@ -593,8 +592,11 @@ public class FileUploadService extends Service implements OnDatatransferProgress
                 // KEY_UPLOAD_TIMESTAMP - TODO use AlarmManager to wake up this service
                 break;
             case FILE_GONE:
-                mDb.updateUploadStatus(uploadDbObject.getLocalPath(), UploadStatus.UPLOAD_FAILED_GIVE_UP,
-                        new RemoteOperationResult(ResultCode.FILE_NOT_FOUND));
+                mUploadsStorageManager.updateUploadStatus(
+                        uploadDbObject.getLocalPath(),
+                        UploadStatus.UPLOAD_FAILED_GIVE_UP,
+                        new RemoteOperationResult(ResultCode.FILE_NOT_FOUND)
+                );
                 if (mPendingUploads.remove(uploadDbObject.getRemotePath()) == null) {
                     Log_OC.w(TAG, "Could remove " + uploadDbObject.getRemotePath()
                             + " from mPendingUploads because it does not exist.");
@@ -713,7 +715,7 @@ public class FileUploadService extends Service implements OnDatatransferProgress
                 // storagePath inside upload is the temporary path. file
                 // contains the correct path used as db reference.
                 upload.getOCFile().setStoragePath(file.getStoragePath());
-                mDb.updateUploadStatus(upload);
+                mUploadsStorageManager.updateUploadStatus(upload);
             }
         }
 
@@ -740,7 +742,7 @@ public class FileUploadService extends Service implements OnDatatransferProgress
             if(upload == null) {
                 Log_OC.e(TAG, "Could not delete upload "+file+" from mPendingUploads.");
             }
-            int d = mDb.removeUpload(file.getStoragePath());
+            int d = mUploadsStorageManager.removeUpload(file.getStoragePath());
             if(d == 0) {
                 Log_OC.e(TAG, "Could not delete upload "+file.getStoragePath()+" from database.");
             }            
@@ -1187,14 +1189,19 @@ public class FileUploadService extends Service implements OnDatatransferProgress
      * Updates the persistent upload database that upload is in progress.
      */
     private void updateDatabaseUploadStart(UploadFileOperation upload) {
-        mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_IN_PROGRESS, null);    
+        mUploadsStorageManager.updateUploadStatus(
+                upload.getOriginalStoragePath(),
+                UploadStatus.UPLOAD_IN_PROGRESS, null
+        );
     }
 
     /**
      * Callback method to update the progress bar in the status notification
      */
     @Override
-    public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
+    public void onTransferProgress(
+            long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath
+    ) {
         int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
         if (percent != mLastPercent) {
             mNotificationBuilder.setProgress(100, percent, false);
@@ -1281,18 +1288,28 @@ public class FileUploadService extends Service implements OnDatatransferProgress
         // result: success or fail notification
         Log_OC.d(TAG, "updateDataseUploadResult uploadResult: " + uploadResult + " upload: " + upload);
         if (uploadResult.isCancelled()) {
-            mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_CANCELLED, uploadResult);
+            mUploadsStorageManager.updateUploadStatus(
+                    upload.getOriginalStoragePath(),
+                    UploadStatus.UPLOAD_CANCELLED,
+                    uploadResult
+            );
         } else {
 
             if (uploadResult.isSuccess()) {
-                mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_SUCCEEDED, uploadResult);
+                mUploadsStorageManager.updateUploadStatus(
+                        upload.getOriginalStoragePath(),
+                        UploadStatus.UPLOAD_SUCCEEDED,
+                        uploadResult
+                );
             } else {
                 // TODO: Disable for testing of menu actions in uploads view
 //                if (shouldRetryFailedUpload(uploadResult)) {
-//                    mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_FAILED_RETRY, uploadResult);
+//                    mUploadsStorageManager.updateUploadStatus(
+//                        upload.getOriginalStoragePath(), UploadStatus.UPLOAD_FAILED_RETRY, uploadResult
+//                    );
 //                } else {
-//                    mDb.updateUploadStatus(upload.getOriginalStoragePath(),
-//                            UploadDbHandler.UploadStatus.UPLOAD_FAILED_GIVE_UP, uploadResult);
+//                    mUploadsStorageManager.updateUploadStatus(upload.getOriginalStoragePath(),
+//                            UploadsStorageManager.UploadStatus.UPLOAD_FAILED_GIVE_UP, uploadResult);
 //                }
             }
         }

+ 9 - 0
src/com/owncloud/android/providers/FileContentProvider.java

@@ -846,6 +846,15 @@ public class FileContentProvider extends ContentProvider {
                 + ProviderTableMeta.UPLOADS_FILE_ID + " INTEGER, "
                 + ProviderTableMeta.UPLOADS_PATH + " TEXT, "
                 + ProviderTableMeta.UPLOADS_STATUS + " INTEGER );" );   // UploadStatus
+
+        /* before:
+        // PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a
+        // bug in some early versions, this is not the case in SQLite.
+        //db.execSQL("CREATE TABLE " + TABLE_UPLOAD + " (" + " path TEXT PRIMARY KEY NOT NULL UNIQUE,"
+        //        + " uploadStatus INTEGER NOT NULL, uploadObject TEXT NOT NULL);");
+        // uploadStatus is used to easy filtering, it has precedence over
+        // uploadObject.getUploadStatus()
+        */
     }
 
     /**

+ 1 - 6
src/com/owncloud/android/ui/activity/Preferences.java

@@ -73,7 +73,7 @@ import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.db.UploadDbHandler;
+import com.owncloud.android.datamodel.UploadsStorageManager;
 import com.owncloud.android.files.FileOperationsHelper;
 import com.owncloud.android.files.services.FileDownloader;
 import com.owncloud.android.files.services.FileUploadService;
@@ -95,8 +95,6 @@ public class Preferences extends PreferenceActivity
     private static final String TAG = "OwnCloudPreferences";
 
 
-    private UploadDbHandler mDbHandler;
-
     private static final int ACTION_SELECT_UPLOAD_PATH = 1;
     private static final int ACTION_SELECT_UPLOAD_VIDEO_PATH = 2;
 
@@ -129,7 +127,6 @@ public class Preferences extends PreferenceActivity
         getDelegate().installViewFactory();
         getDelegate().onCreate(savedInstanceState);
         super.onCreate(savedInstanceState);
-        mDbHandler = UploadDbHandler.getInstance(getBaseContext());
         addPreferencesFromResource(R.xml.preferences);
 
         ActionBar actionBar = getSupportActionBar();
@@ -667,8 +664,6 @@ public class Preferences extends PreferenceActivity
 
     @Override
     protected void onDestroy() {
-        mDbHandler.close();
-
         if (mDownloadServiceConnection != null) {
             unbindService(mDownloadServiceConnection);
             mDownloadServiceConnection = null;

+ 6 - 8
src/com/owncloud/android/ui/activity/UploadListActivity.java

@@ -21,7 +21,6 @@ package com.owncloud.android.ui.activity;
 
 import java.io.File;
 
-import android.accounts.Account;
 import android.content.ActivityNotFoundException;
 import android.content.ComponentName;
 import android.content.Intent;
@@ -38,19 +37,18 @@ import android.widget.Toast;
 
 import com.owncloud.android.R;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.db.UploadDbHandler;
+import com.owncloud.android.datamodel.UploadsStorageManager;
 import com.owncloud.android.db.UploadDbObject;
 import com.owncloud.android.files.services.FileUploadService;
 import com.owncloud.android.files.services.FileUploadService.FileUploaderBinder;
 import com.owncloud.android.lib.common.utils.Log_OC;
-import com.owncloud.android.ui.errorhandling.ExceptionHandler;
 import com.owncloud.android.ui.fragment.UploadListFragment;
 import com.owncloud.android.ui.preview.PreviewImageActivity;
 
 /**
  * Activity listing pending, active, and completed uploads. User can delete
  * completed uploads from view. Content of this list of coming from
- * {@link UploadDbHandler}.
+ * {@link UploadsStorageManager}.
  *
  */
 public class UploadListActivity extends FileActivity implements UploadListFragment.ContainerActivity {
@@ -140,13 +138,13 @@ public class UploadListActivity extends FileActivity implements UploadListFragme
                 break;
             }
             case R.id.action_clear_failed_uploads: {
-                UploadDbHandler db = UploadDbHandler.getInstance(this);
-                db.clearFailedUploads();
+                UploadsStorageManager usm = new UploadsStorageManager(getContentResolver());
+                usm.clearFailedUploads();
                 break;
             }
             case R.id.action_clear_finished_uploads: {
-                UploadDbHandler db = UploadDbHandler.getInstance(this);
-                db.clearFinishedUploads();
+                UploadsStorageManager usm = new UploadsStorageManager(getContentResolver());
+                usm.clearFinishedUploads();
                 break;
             }
             default:

+ 44 - 41
src/com/owncloud/android/ui/adapter/ExpandableUploadListAdapter.java

@@ -25,7 +25,6 @@ import java.util.Comparator;
 import java.util.Observable;
 import java.util.Observer;
 
-import android.app.Activity;
 import android.content.Context;
 import android.database.DataSetObserver;
 import android.graphics.Bitmap;
@@ -44,8 +43,8 @@ import android.widget.TextView;
 import com.owncloud.android.R;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
-import com.owncloud.android.db.UploadDbHandler;
-import com.owncloud.android.db.UploadDbHandler.UploadStatus;
+import com.owncloud.android.datamodel.UploadsStorageManager;
+import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
 import com.owncloud.android.db.UploadDbObject;
 import com.owncloud.android.files.services.FileUploadService;
 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
@@ -62,7 +61,9 @@ import com.owncloud.android.utils.DisplayUtils;
 public class ExpandableUploadListAdapter extends BaseExpandableListAdapter implements Observer {
 
     private static final String TAG = "ExpandableUploadListAdapter";
-    private Activity mActivity;
+    private FileActivity mParentActivity;
+
+    private UploadsStorageManager mUploadsStorageManager;
     
     public ProgressListener mProgressListener; 
     UploadFileOperation mCurrentUpload;
@@ -92,22 +93,16 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         abstract public int getGroupIcon();
     }
     private UploadGroup[] mUploadGroups = null;
-    UploadDbHandler mDb;
 
-    FileActivity parentFileActivity;
-    public void setFileActivity(FileActivity parentFileActivity) {
-        this.parentFileActivity = parentFileActivity;
-    }
-    
-    public ExpandableUploadListAdapter(Activity context) {
+    public ExpandableUploadListAdapter(FileActivity parentActivity) {
         Log_OC.d(TAG, "UploadListAdapter");
-        mActivity = context;
-        mDb = UploadDbHandler.getInstance(mActivity);
+        mParentActivity = parentActivity;
+        mUploadsStorageManager = new UploadsStorageManager(mParentActivity.getContentResolver());
         mUploadGroups = new UploadGroup[3];
         mUploadGroups[0] = new UploadGroup("Current Uploads") {
             @Override
             public void refresh() {
-                items = mDb.getCurrentAndPendingUploads();
+                items = mUploadsStorageManager.getCurrentAndPendingUploads();
                 Arrays.sort(items, comparator);
             }
             @Override
@@ -118,7 +113,7 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         mUploadGroups[1] = new UploadGroup("Failed Uploads"){
             @Override
             public void refresh() {
-                items = mDb.getFailedUploads();
+                items = mUploadsStorageManager.getFailedUploads();
                 Arrays.sort(items, comparator);
             }
             @Override
@@ -130,7 +125,7 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         mUploadGroups[2] = new UploadGroup("Finished Uploads"){
             @Override
             public void refresh() {
-                items = mDb.getFinishedUploads();
+                items = mUploadsStorageManager.getFinishedUploads();
                 Arrays.sort(items, comparator);
             }
             @Override
@@ -145,14 +140,14 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
     @Override
     public void registerDataSetObserver(DataSetObserver observer) {
         super.registerDataSetObserver(observer);
-        mDb.addObserver(this);
+        mUploadsStorageManager.addObserver(this);
         Log_OC.d(TAG, "registerDataSetObserver");
     }
 
     @Override
     public void unregisterDataSetObserver(DataSetObserver observer) {
         super.unregisterDataSetObserver(observer);
-        mDb.deleteObserver(this);
+        mUploadsStorageManager.deleteObserver(this);
         Log_OC.d(TAG, "unregisterDataSetObserver");
     }
 
@@ -164,7 +159,10 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
     private View getView(UploadDbObject[] uploadsItems, int position, View convertView, ViewGroup parent) {
         View view = convertView;
         if (view == null) {
-            LayoutInflater inflator = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+            LayoutInflater inflator =
+                    (LayoutInflater) mParentActivity.getSystemService(
+                            Context.LAYOUT_INFLATER_SERVICE
+                    );
             view = inflator.inflate(R.layout.upload_list_item, null);
         }
         if (uploadsItems != null && uploadsItems.length > position) {
@@ -186,13 +184,13 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
             String status;
             switch (uploadObject.getUploadStatus()) {
             case UPLOAD_IN_PROGRESS:
-                status = mActivity.getResources().getString(R.string.uploader_upload_in_progress_ticker);
+                status = mParentActivity.getString(R.string.uploader_upload_in_progress_ticker);
                 ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.upload_progress_bar);
                 progressBar.setProgress(0);
                 progressBar.setVisibility(View.VISIBLE);
                 mProgressListener = new ProgressListener(progressBar);
-                if(parentFileActivity.getFileUploaderBinder() != null) {
-                    mCurrentUpload = parentFileActivity.getFileUploaderBinder().getCurrentUploadOperation();
+                if(mParentActivity.getFileUploaderBinder() != null) {
+                    mCurrentUpload = mParentActivity.getFileUploaderBinder().getCurrentUploadOperation();
                     if(mCurrentUpload != null) {
                         mCurrentUpload.addDatatransferProgressListener(mProgressListener);
                         Log_OC.d(TAG, "added progress listener for current upload: " + mCurrentUpload);
@@ -200,7 +198,7 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
                         Log_OC.w(TAG, "getFileUploaderBinder().getCurrentUploadOperation() return null. That is odd.");
                     }
                 } else {
-                    Log_OC.e(TAG, "UploadBinder == null. It should have been created on creating parentFileActivity"
+                    Log_OC.e(TAG, "UploadBinder == null. It should have been created on creating mParentActivity"
                             + " which inherits from FileActivity. Fix that!");
                 }
                 break;
@@ -218,14 +216,14 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
                 } else {
                     status = "Upload will be retried shortly.";
                 }
-                String laterReason = FileUploadService.getUploadLaterReason(mActivity, uploadObject);
+                String laterReason = FileUploadService.getUploadLaterReason(mParentActivity, uploadObject);
                 if(laterReason != null) {
                     //Upload failed once but is delayed now, show reason.
                     status += "\n" + laterReason;
                 }
                 break;
             case UPLOAD_LATER:
-                status = FileUploadService.getUploadLaterReason(mActivity, uploadObject);
+                status = FileUploadService.getUploadLaterReason(mParentActivity, uploadObject);
                 break;
             case UPLOAD_SUCCEEDED:
                 status = "Completed.";
@@ -246,11 +244,11 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
             if(uploadObject.getUploadStatus() != UploadStatus.UPLOAD_IN_PROGRESS) {
                 ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.upload_progress_bar);
                 progressBar.setVisibility(View.GONE);
-                if (parentFileActivity.getFileUploaderBinder() != null && mProgressListener != null
+                if (mParentActivity.getFileUploaderBinder() != null && mProgressListener != null
                         && mCurrentUpload != null) {
                     OCFile currentOcFile = mCurrentUpload.getFile();
-                    parentFileActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener,
-                            uploadObject.getAccount(mActivity), currentOcFile);
+                    mParentActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener,
+                            uploadObject.getAccount(mParentActivity), currentOcFile);
                     mProgressListener = null;
                     mCurrentUpload = null;
                 }            
@@ -260,30 +258,30 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
             ImageButton rightButton = (ImageButton) view.findViewById(R.id.upload_right_button);
             if (uploadObject.userCanRetryUpload()
                     && uploadObject.getUploadStatus() != UploadStatus.UPLOAD_SUCCEEDED) {
-                //Refresh
-                rightButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_action_refresh_grey));
-                rightButton.setOnClickListener(new OnClickListener() {                
+                //Refresh   - TODO test buttons in Android 4.x
+                rightButton.setImageDrawable(mParentActivity.getDrawable(R.drawable.ic_action_refresh_grey));
+                rightButton.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {
-                        parentFileActivity.getFileOperationsHelper().retryUpload(uploadObject);                                        
+                        mParentActivity.getFileOperationsHelper().retryUpload(uploadObject);
                     }
                 });
             } else if (uploadObject.userCanCancelUpload()) {
                 //Cancel
-                rightButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_cancel));
+                rightButton.setImageDrawable(mParentActivity.getDrawable(R.drawable.ic_cancel));
                 rightButton.setOnClickListener(new OnClickListener() {                
                     @Override
                     public void onClick(View v) {
-                        parentFileActivity.getFileOperationsHelper().cancelTransference(uploadObject.getOCFile());                                        
+                        mParentActivity.getFileOperationsHelper().cancelTransference(uploadObject.getOCFile());
                     }
                 });
             } else {
                 //Delete
-                rightButton.setImageDrawable(mActivity.getDrawable(R.drawable.ic_delete));
+                rightButton.setImageDrawable(mParentActivity.getDrawable(R.drawable.ic_delete));
                 rightButton.setOnClickListener(new OnClickListener() {                
                     @Override
                     public void onClick(View v) {
-                        parentFileActivity.getFileOperationsHelper().removeUploadFromList(uploadObject);                                        
+                        mParentActivity.getFileOperationsHelper().removeUploadFromList(uploadObject);
                     }
                 });
             }
@@ -300,8 +298,13 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
             }            
 
             TextView uploadDate = (TextView) view.findViewById(R.id.upload_date);
-            CharSequence dateString = DisplayUtils.getRelativeDateTimeString(mActivity, uploadObject.getUploadTime()
-                    .getTimeInMillis(), DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
+            CharSequence dateString = DisplayUtils.getRelativeDateTimeString(
+                    mParentActivity,
+                    uploadObject.getUploadTime().getTimeInMillis(),
+                    DateUtils.SECOND_IN_MILLIS,
+                    DateUtils.WEEK_IN_MILLIS,
+                    0
+            );
             uploadDate.setText(dateString);
         }
 
@@ -318,7 +321,7 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
     
 
     /**
-     * Load upload items from {@link UploadDbHandler}.
+     * Load upload items from {@link UploadsStorageManager}.
      */
     private void loadUploadItemsFromDb() {
         Log_OC.d(TAG, "loadUploadItemsFromDb");
@@ -326,7 +329,7 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         for (UploadGroup group : mUploadGroups) {
             group.refresh();
         }
-        mActivity.runOnUiThread(new Runnable() {
+        mParentActivity.runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 notifyDataSetChanged();
@@ -404,7 +407,7 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         
         UploadGroup group = (UploadGroup) getGroup(groupPosition);
         if (convertView == null) {
-            LayoutInflater infalInflater = (LayoutInflater) mActivity
+            LayoutInflater infalInflater = (LayoutInflater) mParentActivity
                     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             convertView = infalInflater.inflate(R.layout.upload_list_group, null);
         }

+ 2 - 6
src/com/owncloud/android/ui/fragment/UploadListFragment.java

@@ -30,11 +30,9 @@ import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;
-import android.widget.BaseExpandableListAdapter;
 import android.widget.ExpandableListView;
 import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
 import android.widget.ListView;
-import android.widget.TextView;
 
 import com.owncloud.android.R;
 import com.owncloud.android.db.UploadDbObject;
@@ -42,7 +40,6 @@ import com.owncloud.android.lib.common.utils.Log_OC;
 import com.owncloud.android.ui.activity.FileActivity;
 import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.adapter.ExpandableUploadListAdapter;
-import com.owncloud.android.utils.UploadUtils;
 
 /**
  * A Fragment that lists all files and folders in a given LOCAL path.
@@ -86,12 +83,11 @@ public class UploadListFragment extends ExpandableListFragment {
 
     @Override
     public void onActivityCreated(Bundle savedInstanceState) {
-        super.onActivityCreated(savedInstanceState);
         Log_OC.d(TAG, "onActivityCreated() start");
         super.onActivityCreated(savedInstanceState);
-        mAdapter = new ExpandableUploadListAdapter(getActivity());
+        mAdapter = new ExpandableUploadListAdapter((FileActivity)getActivity());
         setListAdapter(mAdapter);
-        mAdapter.setFileActivity(((FileActivity) getActivity()));
+        //mAdapter.setFileActivity(((FileActivity) getActivity()));
         
         registerForContextMenu(getListView());
         getListView().setOnCreateContextMenuListener(this);