it.scoppelletti.mobilepower.app.data.DatabaseConnectionManager.java Source code

Java tutorial

Introduction

Here is the source code for it.scoppelletti.mobilepower.app.data.DatabaseConnectionManager.java

Source

/*
 * Copyright (C) 2014 Dario Scoppelletti, <http://www.scoppelletti.it/>.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package it.scoppelletti.mobilepower.app.data;

import java.util.*;
import android.app.*;
import android.content.*;
import android.database.sqlite.*;
import android.os.*;
import android.support.v4.app.*;
import org.apache.commons.lang3.*;
import it.scoppelletti.mobilepower.app.*;
import it.scoppelletti.mobilepower.data.*;
import it.scoppelletti.mobilepower.os.*;
import it.scoppelletti.mobilepower.ui.resources.R;

/**
 * Gestione della connessione al database.
 * 
 * @since 1.0
 */
public final class DatabaseConnectionManager implements Runnable, DialogInterface.OnCancelListener, AsyncTaskHost {
    private final ActivitySupport myActivity;
    private final String myDbName;
    private final int myVersion;
    private final DatabaseUpgrader myUpgrader;
    private final Handler myHandler;
    private final List<OnDatabaseConnectionListener> myOnDbListeners;
    private SQLiteDatabase myDb;
    private DatabaseUpgradeTask myUpgradeTask;
    private boolean myUpgraded;

    /**
     * Costruttore.
     * 
     * @param activity Attivit&agrave;.
     * @param dbName   Nome del database.
     * @param version  Numero di versione del database.
     * @param upgrader Procedura di aggiornamento.
     */
    public DatabaseConnectionManager(ActivitySupport activity, String dbName, int version,
            DatabaseUpgrader upgrader) {
        if (activity == null) {
            throw new NullPointerException("Argument activity is null.");
        }
        if (StringUtils.isBlank(dbName)) {
            throw new NullPointerException("Argument dbName is null.");
        }
        if (version < 1) {
            throw new IllegalArgumentException("Argument versione < 1.");
        }
        if (upgrader == null) {
            throw new NullPointerException("Argument upgrader is null.");
        }

        myActivity = activity;
        myDbName = dbName;
        myVersion = version;
        myUpgrader = upgrader;
        myHandler = new Handler();
        myOnDbListeners = new ArrayList<OnDatabaseConnectionListener>(1);
        myUpgraded = false;
    }

    /**
     * Aggiunge un gestore degli eventi di connessione al database.
     * 
     * @param obj Oggetto.
     */
    public void addOnDatabaseConnectionListener(OnDatabaseConnectionListener obj) {
        if (obj == null) {
            throw new NullPointerException("Argument obj is null.");
        }

        myOnDbListeners.add(obj);
        if (myDb != null) {
            // La connessione e' gia' aperta:
            // Lo comunico immediatamente al nuovo gestore.
            obj.onDatabaseOpen(myDb);
        }
    }

    /**
     * Rimuove un gestore degli eventi di connessione al database.
     * 
     * @param obj Oggetto.
     */
    public void removeOnDatabaseConnectionListener(OnDatabaseConnectionListener obj) {
        myOnDbListeners.remove(obj);
    }

    /**
     * Schedula l&rsquo;eventuale aggiornamento del database.
     */
    public void upgrade() {
        myHandler.post(this);
    }

    /**
     * Esegue l&rsquo;eventuale aggiornamento del database.
     */
    public void run() {
        int ver, stepCount;
        Bundle params;
        ProgressDialogFragment dlg;
        FragmentManager fragmentMgr;

        if (myDb != null) {
            throw new IllegalStateException("Database already open.");
        }

        myDb = myActivity.asActivity().openOrCreateDatabase(myDbName, Context.MODE_PRIVATE, null);
        ver = myDb.getVersion();
        if (ver >= myVersion) {
            onPostExecute(0, null, false);
            return;
        }

        stepCount = myVersion - ver;
        fragmentMgr = myActivity.getSupportFragmentManager();
        dlg = ProgressDialogFragment.newInstance(R.string.lbl_databaseUpgrading, stepCount, true);
        dlg.setOnCancelListener(this);
        dlg.show(fragmentMgr, ProgressDialogFragment.TAG);

        myUpgradeTask = new DatabaseUpgradeTask(myDb, myUpgrader, stepCount, this);
        params = new Bundle();
        params.putInt(DatabaseUpgradeTask.PARAM_CURRENTVERSION, ver);
        params.putInt(DatabaseUpgradeTask.PARAM_TARGETVERSION, myVersion);
        myUpgradeTask.execute(params);
    }

    /**
     * Ripristino dell&rsquo;attivit&agrave;.
     */
    public void onResume() {
        if (!myUpgraded) {
            return;
        }

        myDb = myActivity.asActivity().openOrCreateDatabase(myDbName, Context.MODE_PRIVATE, null);
        for (OnDatabaseConnectionListener listener : myOnDbListeners) {
            listener.onDatabaseOpen(myDb);
        }
    }

    /**
     * Pausa dell&rsquo;attivit&agrave;.
     */
    public void onPause() {
        if (myUpgradeTask != null) {
            myUpgradeTask.cancel(true);
            myUpgradeTask = null;
        }

        if (myDb != null) {
            myDb.close();
            myDb = null;
            for (OnDatabaseConnectionListener listener : myOnDbListeners) {
                listener.onDatabaseClosed();
            }
        }
    }

    /**
     * Gestisce l&rsquo;interruzione dell&rsquo;aggiornamento del database. 
     */
    public void onCancel(DialogInterface dialog) {
        Activity activity;

        if (myUpgradeTask != null) {
            myUpgradeTask.cancel(true);
            myUpgradeTask = null;
        }

        if (myDb != null) {
            myDb.close();
            myDb = null;
        }

        activity = myActivity.asActivity();
        if (!activity.isFinishing()) {
            activity.finish();
        }
    }

    public void onPostExecute(int requestCode, Bundle result, boolean cancelled) {
        if (result != null) {
            myUpgradeTask = null;
            ProgressDialogFragment.dismiss(myActivity.getSupportFragmentManager(), ProgressDialogFragment.TAG);
        }

        if (cancelled) {
            onCancel(null);
            return;
        }

        for (OnDatabaseConnectionListener listener : myOnDbListeners) {
            listener.onDatabaseOpen(myDb);
        }

        myUpgraded = true;
    }

    public void onProgressUpdate(int requestCode, int progress) {
        ProgressDialogFragment.setProgress(myActivity.getSupportFragmentManager(), ProgressDialogFragment.TAG,
                progress);
    }
}