fr.eoit.activity.StockActivity.java Source code

Java tutorial

Introduction

Here is the source code for fr.eoit.activity.StockActivity.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.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.bugsense.trace.BugSenseHandler;
import fr.eo.exception.DownloadException;
import fr.eo.exception.ParsingException;
import fr.eoit.R;
import fr.eoit.activity.listener.ItemOnItemListClickListener;
import fr.eoit.activity.util.AmazingListView;
import fr.eoit.activity.util.AmazingSimpleCursorAdapter;
import fr.eoit.activity.util.AmazingSimpleCursorAdapter.OrderType;
import fr.eoit.activity.util.ItemListViewBinder;
import fr.eoit.bean.AssetItemBean;
import fr.eoit.bean.ItemBeanWithMaterials;
import fr.eoit.db.DatabaseHelper;
import fr.eoit.db.bean.Item;
import fr.eoit.db.bean.Stock;
import fr.eoit.db.dto.ColumnsNames;
import fr.eoit.parameter.Parameters;
import fr.eoit.parameter.station.Stations;
import fr.eoit.util.AndroidUrlDownloader;
import fr.eoit.util.SparseItemBeanArray;
import fr.eoit.xml.asset.AssetXmlParser;
import fr.piconsoft.db.util.DbUtil;

/**
 * @author picon.software
 */
public class StockActivity extends LoaderActivity<Cursor> {

    private static final String LOG_TAG = StockActivity.class.getSimpleName();

    private OrderType orderType = OrderType.CATEGORY;
    private AmazingSimpleCursorAdapter adapter;

    public StockActivity() {
        super(Window.FEATURE_PROGRESS);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.stock);

        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(Stock.CONTENT_URI);
        }

        // The names of the cursor columns to display in the view, initialized to the title column
        String[] dataColumns = { Stock.COLUMN_NAME_ITEM_ID, Item.COLUMN_NAME_NAME, Stock.COLUMN_NAME_QUANTITY };

        // The view IDs that will display the cursor columns, initialized to the TextView in
        // noteslist_item.xml
        int[] viewIDs = { R.id.ITEM_ICON, R.id.ITEM_NAME, R.id.ITEM_QUANTITY };

        // Creates the backing adapter for the ListView.
        adapter = new AmazingSimpleCursorAdapter(this, R.layout.row, dataColumns, viewIDs);

        adapter.setViewBinder(new ItemListViewBinder());

        AmazingListView stockListView = (AmazingListView) findViewById(R.id.ITEM_LIST);
        stockListView.setOnItemClickListener(new ItemOnItemListClickListener());
        stockListView
                .setPinnedHeaderView(LayoutInflater.from(this).inflate(R.layout.row_header, stockListView, false));

        // Sets the ListView's adapter to be the cursor adapter that was just created.
        stockListView.setAdapter(adapter);

        initOrRestart();
    }

    @Override
    protected void onReload() {
        super.onReload();

        initOrRestart();
    }

    @Override
    public Loader<Cursor> getCursorLoader(int id, Bundle args) {
        return new CursorLoader(this, getIntent().getData(),
                new String[] { Stock.COLUMN_NAME_ITEM_ID + " AS " + Stock._ID, Item.COLUMN_NAME_NAME,
                        Stock.COLUMN_NAME_ITEM_ID, Stock.COLUMN_NAME_QUANTITY,
                        ColumnsNames.Categories.COLUMN_NAME_NAME_ALIAS },
                //Stock.COLUMN_NAME_LOCATION_ID + " = " + Stations.getProductionStation().stationId,
                null, null, orderType == OrderType.NAME_ALPHA ? "i." + Item.COLUMN_NAME_NAME
                        : ColumnsNames.Categories.COLUMN_NAME_NAME_ALIAS);
    }

    @Override
    public void onLoadFinished(Cursor data) {
        setActionBarTitle(R.string.stock);
        setActionBarSubtitle(Stations.getProductionStation().stationName);

        adapter.swapCursor(data);
        if (DbUtil.hasAtLeastOneRow(data)) {
            findViewById(R.id.ITEM_LIST).setVisibility(View.VISIBLE);
            findViewById(android.R.id.empty).setVisibility(View.GONE);
        } else {
            findViewById(R.id.ITEM_LIST).setVisibility(View.GONE);
            findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
        }

        setActionBarInderterminate(false);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        adapter.swapCursor(null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.stockmenu, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.PARAMETERS_OPTION:
            final Intent paramIntent = new Intent(this, ParameterActivity.class);
            startActivity(paramIntent);
            return true;
        case R.id.LOCATION_MANAGEMENT_OPTION:
            final Intent locationManagementIntent = new Intent(this, LocationManagementActivity.class);
            startActivity(locationManagementIntent);
            return true;
        case R.id.REFRESH_OPTION:
            setActionBarInderterminate(true);

            new StockUpdaterAsyncTask().execute(getApplicationContext());
            return true;

        default:
            return false;
        }
    }

    private class StockUpdaterAsyncTask extends AsyncTask<Context, Integer, Void> {

        private int errorMsgId;

        @Override
        protected Void doInBackground(Context... context) {
            try {
                SparseItemBeanArray assets = new AssetXmlParser(new AndroidUrlDownloader(), Xml.newPullParser(),
                        Parameters.keyId, Parameters.vCode, Parameters.characterId)
                                .getAssets(getApplicationContext());

                publishProgress(0);

                SQLiteDatabase db = new DatabaseHelper(context[0]).getWritableDatabase();
                db.execSQL("DELETE FROM " + Stock.TABLE_NAME + ";");
                db.close();

                int cpt = 1;
                for (ItemBeanWithMaterials item : assets.values()) {
                    ContentValues values = new ContentValues();
                    AssetItemBean asset = (AssetItemBean) item;
                    values.put(Stock.COLUMN_NAME_ITEM_ID, asset.id);
                    values.put(Stock.COLUMN_NAME_QUANTITY, asset.quantity);
                    values.put(Stock.COLUMN_NAME_LOCATION_ID, asset.locationId);

                    getContentResolver().insert(Stock.CONTENT_URI, values);

                    publishProgress((int) (cpt * (10000f / assets.size())));
                    cpt++;
                }

                publishProgress(10000);
            } catch (ParsingException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                cancel(true);
                errorMsgId = R.string.api_parsing_error;
                BugSenseHandler.sendException(e);
            } catch (DownloadException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                cancel(true);
                errorMsgId = R.string.api_download_error;
                BugSenseHandler.sendException(e);
            }

            return null;
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(getApplicationContext(), errorMsgId, Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onPostExecute(Void result) {
            getContentResolver().notifyChange(Stock.CONTENT_URI, null);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            int progress = values[0];

            if (progress == 0) {
                setProgressBarIndeterminate(false);
            }

            setProgress(progress);
        }
    }
}