Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit c21cf96e authored by yazhan's avatar yazhan Committed by Zhao Wei Liew
Browse files

CMFileManager: Save history records when quitting

Upon quitting the app, the history records will be lost as
they are not saved. Save the history records so that
the user can access them even after quitting the app.

Change-Id: Ie59a4848de118841d2f3c5ec4805f2add0a1d701
CRs-Fixed: 993150
parent 9ba628b7
Loading
Loading
Loading
Loading
+216 −8
Original line number Diff line number Diff line
@@ -22,6 +22,8 @@ import android.app.Dialog;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
@@ -40,6 +42,7 @@ import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.storage.StorageVolume;
import android.provider.Settings;
@@ -431,8 +434,17 @@ public class NavigationActivity extends Activity
     * @hide
     */
    ListView mEasyModeListView;

    /**
     * Used to record the operation steps
     */
    private List<History> mHistory;

    /**
     * Used to record the items saved in database
     */
    private List<History> mHistorySaved;

    private static final List<MimeTypeCategory> EASY_MODE_LIST = new ArrayList<MimeTypeCategory>() {
        {
            add(NONE);
@@ -498,6 +510,7 @@ public class NavigationActivity extends Activity
    Handler mHandler;

    private AsyncTask<Void, Void, Boolean> mBookmarksTask;
    private AsyncTask<Void, Void, Boolean> mHistoryTask;

    private static final int REQUEST_CODE_STORAGE_PERMS = 321;
    private boolean hasPermissions() {
@@ -658,6 +671,7 @@ public class NavigationActivity extends Activity
        // Initialize navigation drawer
        initDrawer();
        initBookmarks();
        initHistory();

        // Adjust layout (only when start on landscape mode)
        int orientation = getResources().getConfiguration().orientation;
@@ -886,6 +900,7 @@ public class NavigationActivity extends Activity
     */
    private void init() {
        this.mHistory = new ArrayList<History>();
        this.mHistorySaved = new ArrayList<History>();
        this.mChRooted = FileManagerApplication.getAccessMode().compareTo(AccessMode.SAFE) == 0;
    }

@@ -1112,9 +1127,9 @@ public class NavigationActivity extends Activity
            public void onClick(View v) {
                final int index = mDrawerHistory.indexOfChild(v);
                final int count = mDrawerHistory.getChildCount();
                final History history = mHistory.get(count - index - 1);
                final History history = mHistorySaved.get(count - index - 1);

                navigateToHistory(history);
                navigateToHistory(history, true);
                mDrawerLayout.closeDrawer(Gravity.START);
            }
        });
@@ -1372,6 +1387,61 @@ public class NavigationActivity extends Activity
        mBookmarksTask.execute();
    }

    /**
     * Method that initializes the history.
     */
    private synchronized void initHistory() {
        if (mHistoryTask != null &&
                !mHistoryTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
            return;
        }

        // Load history in background
        mHistoryTask = new AsyncTask<Void, Void, Boolean>() {
            Exception mCause;

            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    loadHistory();
                    return Boolean.TRUE;
                }
                catch (Exception e) {
                    this.mCause = e;
                    return Boolean.FALSE;
                }
            }

            @Override
            protected void onPreExecute() {
                mDrawerHistory.removeAllViews();
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (result.booleanValue()) {
                    for (int i = 0; i < mHistory.size(); i++) {
                        final History history = mHistory.get(i);
                        addHistoryToDrawer(i, history.getItem());
                    }
                } else {
                    if (this.mCause != null) {
                        ExceptionUtil.translateException(
                                NavigationActivity.this, this.mCause);
                    }
                }
                mHistoryTask = null;
                mHistory.clear();
            }

            @Override
            protected void onCancelled() {
                mHistoryTask = null;
            }
        };
        mHistoryTask.execute();
    }

    /**
     * Method that loads all kind of bookmarks and join in an array to be used
     * in the listview adapter.
@@ -1600,6 +1670,89 @@ public class NavigationActivity extends Activity
        return bookmarks;
    }

    /**
     * Method that loads the history saved in database.
     */
    private void loadHistory() {
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(
                History.Columns.CONTENT_URI,
                History.Columns.HISTORY_QUERY_COLUMNS,
                null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    String title = cursor.getString(1);
                    String desc = cursor.getString(2);
                    HistoryItem item = new HistoryItem(title, desc);
                    History history = new History(mHistory.size(), item);

                    mHistory.add(history);
                    mHistorySaved.add(history);
                } while (cursor.moveToNext());
            }
        } finally {
            try {
                if (cursor != null) {
                    cursor.close();
                }
            } catch (Exception e) {
                // Ignore
            }
        }
    }

    /**
     * Method that saves the history to the database.
     *
     * @param historyItem
     * @return boolean
     */
    private boolean addHistory(HistoryNavigable historyItem) {
        ContentValues values = new ContentValues(2);
        values.put(History.Columns.TITLE, historyItem.getTitle());
        values.put(History.Columns.DESCRIPTION, historyItem.getDescription());

        final Uri uri = getContentResolver()
                .insert(History.Columns.CONTENT_URI, values);
        if ((int) ContentUris.parseId(uri) == -1) {
            if (DEBUG) {
                Log.e(TAG, "Error inserting the navigation history");
            }
            return false;
        }

        return true;
    }

    /**
     * Method that clears the history database.
     */
    private void deleteAllHistorys() {
        getContentResolver().delete(History.Columns.CONTENT_URI, "", null);
    }

    /**
     * Method that decides if the history item should be saved to database.
     *
     * @param historyItem the history item to be saved to database
     * @return boolean
     */
    private boolean shouldAddHistory(HistoryNavigable historyItem) {
        final String description = historyItem.getDescription();
        if (description == null) {
            return false;
        }

        for (History history : mHistorySaved) {
            String desc = history.getItem().getDescription();
            if (desc != null && desc.equals(description)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Method that initializes the navigation views of the activity
     */
@@ -2098,10 +2251,17 @@ public class NavigationActivity extends Activity
     */
    @Override
    public void onNewHistory(HistoryNavigable navigable) {
        addHistoryToDrawer(this.mHistory.size(), navigable);
        //Recollect information about current status
        History history = new History(this.mHistory.size(), navigable);
        this.mHistory.add(history);
        if (!shouldAddHistory(navigable)) {
            return;
        }
        // Show history in the navigation drawer
        addHistoryToDrawer(this.mHistory.size() - 1, navigable);
        mHistorySaved.add(history);
        // Add history to the database
        addHistory(navigable);
    }

    /**
@@ -2368,20 +2528,31 @@ public class NavigationActivity extends Activity
     */
    private void clearHistory() {
        this.mHistory.clear();
        mHistorySaved.clear();
        mDrawerHistory.removeAllViews();
        mDrawerHistoryEmpty.setVisibility(View.VISIBLE);

        // Delete all history items in the database
        deleteAllHistorys();
    }

    /**
     * Method that navigates to the passed history reference.
     *
     * @param history The history reference
     * @param isFromSavedHistory Whether this is called by saved history item
     * @return boolean A problem occurs while navigate
     */
    public synchronized boolean navigateToHistory(History history) {
    public synchronized boolean navigateToHistory(
            History history, boolean isFromSavedHistory) {
        try {
            //Gets the history
            History realHistory = this.mHistory.get(history.getPosition());
            final History realHistory;
            if (isFromSavedHistory) {
                realHistory = mHistorySaved.get(history.getPosition());
            } else {
                realHistory = mHistory.get(history.getPosition());
            }

            //Navigate to item. Check what kind of history is
            if (realHistory.getItem() instanceof NavigationViewInfoParcelable) {
@@ -2403,6 +2574,17 @@ public class NavigationActivity extends Activity
                searchIntent.setAction(SearchActivity.ACTION_RESTORE);
                searchIntent.putExtra(SearchActivity.EXTRA_SEARCH_RESTORE, (Parcelable)info);
                startActivityForResult(searchIntent, INTENT_REQUEST_SEARCH);
            } else if (realHistory.getItem() instanceof HistoryItem) {
                final String path = realHistory.getItem().getDescription();
                final FileSystemObject fso = CommandHelper.getFileInfo(
                        getApplicationContext(), path, null);
                if (fso != null) {
                    performHideEasyMode();
                    performShowBackArrow(
                            !mDrawerToggle.isDrawerIndicatorEnabled());
                    getCurrentNavigationView().open(fso);
                    mDrawerLayout.closeDrawer(Gravity.START);
                }
            } else {
                //The type is unknown
                throw new IllegalArgumentException("Unknown history type"); //$NON-NLS-1$
@@ -2412,7 +2594,6 @@ public class NavigationActivity extends Activity
            int cc = realHistory.getPosition();
            for (int i = this.mHistory.size() - 1; i >= cc; i--) {
                this.mHistory.remove(i);
                mDrawerHistory.removeViewAt(0);
            }

            if (mDrawerHistory.getChildCount() == 0) {
@@ -2420,7 +2601,8 @@ public class NavigationActivity extends Activity
            }

            //Navigate
            boolean clearHistory = mHistoryTab.isSelected() && mHistory.size() > 0;
            final boolean clearHistory =
                    mHistoryTab.isSelected() && mHistorySaved.size() > 0;
            mClearHistory.setVisibility(clearHistory ? View.VISIBLE : View.GONE);
            return true;

@@ -2478,7 +2660,7 @@ public class NavigationActivity extends Activity

        //Navigate to history
        if (this.mHistory.size() > 0) {
            return navigateToHistory(this.mHistory.get(this.mHistory.size() - 1));
            return navigateToHistory(mHistory.get(mHistory.size() - 1), false);
        }

        //Nothing to apply
@@ -2961,4 +3143,30 @@ public class NavigationActivity extends Activity
    public void updateActiveDialog(Dialog dialog) {
        mActiveDialog = dialog;
    }

    private class HistoryItem extends HistoryNavigable {
        private final String mTitle;
        private final String mDescription;

        public HistoryItem(String title, String description) {
            mTitle = title;
            mDescription = description;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {}

        public String getTitle() {
            return mTitle;
        }

        public String getDescription() {
            return mDescription;
        }
    }
}
+61 −0
Original line number Diff line number Diff line
@@ -16,7 +16,11 @@

package com.cyanogenmod.filemanager.model;

import android.net.Uri;
import android.provider.BaseColumns;

import com.cyanogenmod.filemanager.parcelables.HistoryNavigable;
import com.cyanogenmod.filemanager.providers.BookmarksContentProvider;

import java.io.Serializable;

@@ -42,6 +46,63 @@ public class History implements Serializable, Comparable<History> {
        this.mItem = item;
    }

    /**
     * Columns of the database
     */
    public static class Columns implements BaseColumns {
        /**
         * The content:// style URL for this table
         */
        public static final Uri CONTENT_URI =
                Uri.parse(String.format(
                        "%s%s/%s", //$NON-NLS-1$
                        "content://", //$NON-NLS-1$
                        BookmarksContentProvider.AUTHORITY,
                        "/history")); //$NON-NLS-1$

        /**
         * The title of the history
         * <P>Type: TEXT</P>
         */
        public static final String TITLE = "title"; //$NON-NLS-1$

        /**
         * The description of the history
         * <P>Type: TEXT</P>
         */
        public static final String DESCRIPTION = "description"; //$NON-NLS-1$

        /**
         * The default sort order for this table
         */
        public static final String DEFAULT_SORT_ORDER =
                DESCRIPTION + " ASC"; //$NON-NLS-1$

        /**
         * @hide
         */
        public static final String[] HISTORY_QUERY_COLUMNS =
                { _ID, TITLE, DESCRIPTION };

        /**
         * These save calls to cursor.getColumnIndexOrThrow()
         * THEY MUST BE KEPT IN SYNC WITH ABOVE QUERY COLUMNS
         *
         * @hide
         */
        public static final int HISTORY_ID_INDEX = 0;

        /**
         * @hide
         */
        public static final int HISTORY_TITLE_INDEX = 1;

        /**
         * @hide
         */
        public static final int HISTORY_DESCRIPTION_INDEX = 2;
    }

    /**
     * Method that returns the position of the history.
     *
+5 −0
Original line number Diff line number Diff line
@@ -51,6 +51,11 @@ public class BookmarksDatabaseHelper extends SQLiteOpenHelper {
        db.execSQL("CREATE TABLE bookmarks (" + //$NON-NLS-1$
                   "_id INTEGER PRIMARY KEY," + //$NON-NLS-1$
                   "path TEXT);"); //$NON-NLS-1$

        db.execSQL("CREATE TABLE history (" + //$NON-NLS-1$
                "_id INTEGER PRIMARY KEY," + //$NON-NLS-1$
                "title TEXT," + //$NON-NLS-1$
                "description TEXT);"); //$NON-NLS-1$
    }

    /**
+59 −5
Original line number Diff line number Diff line
@@ -29,6 +29,7 @@ import android.text.TextUtils;
import android.util.Log;

import com.cyanogenmod.filemanager.model.Bookmark;
import com.cyanogenmod.filemanager.model.History;
import com.cyanogenmod.filemanager.preferences.BookmarksDatabaseHelper;

/**
@@ -44,6 +45,8 @@ public class BookmarksContentProvider extends ContentProvider {

    private static final int BOOKMARKS = 1;
    private static final int BOOKMARKS_ID = 2;
    private static final int HISTORY = 3;
    private static final int HISTORY_ID = 4;

    /**
     * The authority string name.
@@ -60,6 +63,13 @@ public class BookmarksContentProvider extends ContentProvider {
        sURLMatcher.addURI(
                AUTHORITY,
                "bookmarks/#", BOOKMARKS_ID); //$NON-NLS-1$

        sURLMatcher.addURI(
                AUTHORITY,
                "history", HISTORY); //$NON-NLS-1$
        sURLMatcher.addURI(
                AUTHORITY,
                "history/#", HISTORY_ID); //$NON-NLS-1$
    }

    /**
@@ -97,6 +107,14 @@ public class BookmarksContentProvider extends ContentProvider {
                qb.appendWhere("_id="); //$NON-NLS-1$
                qb.appendWhere(url.getPathSegments().get(1));
                break;
            case HISTORY:
                qb.setTables("history"); //$NON-NLS-1$
                break;
            case HISTORY_ID:
                qb.setTables("history"); //$NON-NLS-1$
                qb.appendWhere("_id="); //$NON-NLS-1$
                qb.appendWhere(url.getPathSegments().get(1));
                break;
            default:
                throw new IllegalArgumentException("Unknown URL " + url); //$NON-NLS-1$
        }
@@ -127,6 +145,10 @@ public class BookmarksContentProvider extends ContentProvider {
                return "vnd.android.cursor.dir/bookmarks"; //$NON-NLS-1$
            case BOOKMARKS_ID:
                return "vnd.android.cursor.item/bookmarks"; //$NON-NLS-1$
            case HISTORY:
                return "vnd.android.cursor.dir/history"; //$NON-NLS-1$
            case HISTORY_ID:
                return "vnd.android.cursor.item/history"; //$NON-NLS-1$
            default:
                throw new IllegalArgumentException("Unknown URL"); //$NON-NLS-1$
        }
@@ -149,6 +171,13 @@ public class BookmarksContentProvider extends ContentProvider {
                        "bookmarks", values, "_id=" + rowId, null); //$NON-NLS-1$ //$NON-NLS-2$
                break;
            }
            case HISTORY_ID: {
                final String segment = url.getPathSegments().get(1);
                rowId = Long.parseLong(segment);
                count = db.update(
                        "history", values, "_id=" + rowId, null); //$NON-NLS-1$ //$NON-NLS-2$
                break;
            }
            default: {
                throw new UnsupportedOperationException(
                        "Cannot update URL: " + url); //$NON-NLS-1$
@@ -168,20 +197,31 @@ public class BookmarksContentProvider extends ContentProvider {
     */
    @Override
    public Uri insert(Uri url, ContentValues initialValues) {
        if (sURLMatcher.match(url) != BOOKMARKS) {
        if (sURLMatcher.match(url) != BOOKMARKS
                && sURLMatcher.match(url) != HISTORY) {
            throw new IllegalArgumentException("Cannot insert into URL: " + url); //$NON-NLS-1$
        }

        // Add the bookmark
        SQLiteDatabase db = this.mOpenHelper.getWritableDatabase();
        long rowId = db.insert("bookmarks", null, initialValues); //$NON-NLS-1$
        String tablename = null;
        Uri uri = null;

        if (sURLMatcher.match(url) == BOOKMARKS) {
            tablename = "bookmarks";
            uri = Bookmark.Columns.CONTENT_URI;
        } else {
            tablename = "history";
            uri = History.Columns.CONTENT_URI;
        }
        long rowId = db.insert(tablename, null, initialValues); //$NON-NLS-1$
        if (rowId < 0) {
            throw new SQLException("Failed to insert row"); //$NON-NLS-1$
        }
        if (DEBUG) {
            Log.v(TAG, "Added bookmark rowId = " + rowId); //$NON-NLS-1$
            Log.v(TAG, "Added" + tablename + "rowId = " + rowId); //$NON-NLS-1$
        }
        Uri newUrl = ContentUris.withAppendedId(Bookmark.Columns.CONTENT_URI, rowId);
        Uri newUrl = ContentUris.withAppendedId(uri, rowId);

        // Notify changes
        getContext().getContentResolver().notifyChange(newUrl, null);
@@ -201,7 +241,7 @@ public class BookmarksContentProvider extends ContentProvider {
                count = db.delete("bookmarks", whereQuery, whereArgs); //$NON-NLS-1$
                break;
            case BOOKMARKS_ID:
                String segment = url.getPathSegments().get(1);
                final String segment = url.getPathSegments().get(1);
                if (TextUtils.isEmpty(whereQuery)) {
                    whereQuery = "_id=" + segment; //$NON-NLS-1$
                } else {
@@ -210,6 +250,20 @@ public class BookmarksContentProvider extends ContentProvider {
                }
                count = db.delete("bookmarks", whereQuery, whereArgs); //$NON-NLS-1$
                break;
            case HISTORY:
                db.execSQL("delete from history");
                count = 0;
                break;
            case HISTORY_ID:
                String segment_h = url.getPathSegments().get(1);
                if (TextUtils.isEmpty(whereQuery)) {
                    whereQuery = "_id=" + segment_h; //$NON-NLS-1$
                } else {
                    whereQuery = "_id=" + segment_h + //$NON-NLS-1$
                            " AND (" + whereQuery + ")"; //$NON-NLS-1$ //$NON-NLS-2$
                }
                count = db.delete("history", whereQuery, whereArgs); //$NON-NLS-1$
                break;
            default:
                throw new IllegalArgumentException("Cannot delete from URL: " + url); //$NON-NLS-1$
        }