fr.eoit.activity.EOITActivity.java Source code

Java tutorial

Introduction

Here is the source code for fr.eoit.activity.EOITActivity.java

Source

/*
 * Copyright (C) 2012 Picon software
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package fr.eoit.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.*;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.widget.ProgressBar;
import android.widget.TextView;
import fr.eoit.EOITConst;
import fr.eoit.R;
import fr.eoit.db.DatabaseHelper;
import fr.eoit.db.bean.Groups;
import fr.eoit.db.dto.ColumnsNames;
import fr.eoit.db.util.DatabaseUpgradeCallbacks;
import fr.piconsoft.db.util.DbUtil;

import java.io.File;

public class EOITActivity extends LoaderActivity<Cursor> {

    private ProgressBar bar;
    private TextView infoTextView;
    private boolean updated = false;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        loadParametersOnCreate = false;

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        disableConnectionReuseIfNecessary();
        enableHttpResponseCache();

        bar = (ProgressBar) findViewById(R.id.progressBar);
        bar.setIndeterminate(true);
        infoTextView = (TextView) findViewById(R.id.textView);

        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();

        if (blockSize * availableBlocks > EOITConst.APPLICATION_SIZE) {
            new LoadItemsAsyncTask().execute(this);
        } else {
            new AlertDialog.Builder(this).setCancelable(false).setTitle(R.string.database_no_space)
                    .setMessage(getResources().getString(R.string.database_no_space_message,
                            EOITConst.APPLICATION_SIZE / (1024 * 1024)))
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setNegativeButton(R.string.database_locked_close_button_message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    finish();
                                }
                            })
                    .create().show();
        }
    }

    @SuppressWarnings("deprecation")
    private void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    private void enableHttpResponseCache() {
        try {
            long httpCacheSize = 3 * 1024 * 1024; // 3 MiB
            File httpCacheDir = new File(getCacheDir(), "http");
            Class.forName("android.net.http.HttpResponseCache").getMethod("install", File.class, long.class)
                    .invoke(null, httpCacheDir, httpCacheSize);
        } catch (Exception httpResponseCacheNotAvailable) {
            // nothing done
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private class LoadItemsAsyncTask extends AsyncTask<EOITActivity, Integer, EOITActivity>
            implements DatabaseUpgradeCallbacks {

        @Override
        protected EOITActivity doInBackground(EOITActivity... params) {
            EOITActivity activity = params[0];

            try {
                new DatabaseHelper(getApplicationContext(), this).getWritableDatabase().close();

                if (updated) {
                    onInfoTextUpdate(R.string.compact_db);
                    SQLiteDatabase db = new DatabaseHelper(getApplicationContext(), this).getWritableDatabase();
                    db.execSQL("VACUUM;");
                    db.close();
                }
            } catch (SQLiteException e) {
                this.cancel(true);
                return activity;
            }

            return activity;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            infoTextView.setText(values[0]);
        }

        @Override
        protected void onPostExecute(EOITActivity activity) {
            super.onPostExecute(activity);

            getSupportLoaderManager().initLoader(0, null, activity);

            Intent intent = new Intent(activity, ItemListActivity.class);
            startActivity(intent);
            activity.finish();
        }

        @Override
        protected void onCancelled() {
            new AlertDialog.Builder(EOITActivity.this).setCancelable(false).setTitle(R.string.database_locked)
                    .setMessage(R.string.database_locked_message).setIcon(android.R.drawable.ic_dialog_alert)
                    .setNegativeButton(R.string.database_locked_close_button_message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    finish();
                                }
                            })
                    .create().show();
        }

        /**
         * @see fr.eoit.db.util.DatabaseUpgradeCallbacks#onProgressBarReset(int)
         */
        @Override
        public void onProgressBarReset(int max) {
            bar.setMax(max);
        }

        /**
         * @see fr.eoit.db.util.DatabaseUpgradeCallbacks#onProgressBarIncrementUpdate(int)
         */
        @Override
        public void onProgressBarIncrementUpdate(int diff) {
            bar.incrementProgressBy(diff);
        }

        /**
         * @see fr.eoit.db.util.DatabaseUpgradeCallbacks#onProgressBarIndeterminate(boolean)
         */
        @Override
        public void onProgressBarIndeterminate(boolean indeterminate) {
            bar.setIndeterminate(indeterminate);
        }

        /**
         * @see fr.eoit.db.util.DatabaseUpgradeCallbacks#onInfoTextUpdate(int)
         */
        @Override
        public void onInfoTextUpdate(int resId) {
            publishProgress(resId);
        }

        @Override
        public void onUpgradeStart() {
            updated = true;
        }

        @Override
        public void onUpgradeEnd() {
        }
    }

    @Override
    public Loader<Cursor> getCursorLoader(int id, Bundle args) {
        return new CursorLoader(this, Groups.CONTENT_URI,
                new String[] { Groups._ID, Groups.COLUMN_NAME_CATEGORIE_ID,
                        "c." + ColumnsNames.Categories.COLUMN_NAME_NAME, "g." + Groups.COLUMN_NAME_NAME },
                null, null, "g." + Groups._ID);
    }

    @Override
    public void onLoadFinished(Cursor cursor) {
        if (DbUtil.hasAtLeastOneRow(cursor)) {

            while (!cursor.isAfterLast()) {

                cursor.moveToNext();
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursor) {
    }
}