io.github.romankl.bitcoinvalue.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for io.github.romankl.bitcoinvalue.MainActivity.java

Source

/************************************************************************************************************
 * Copyright (C) 2014 - 2015  Roman Klauke                                                                  *
 *                                                                                                          *
 *     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 3 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, see <http://www.gnu.org/licenses/>.                                *
 ************************************************************************************************************/

package io.github.romankl.bitcoinvalue;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import org.joda.time.DateTime;

import butterknife.ButterKnife;
import butterknife.InjectView;
import io.github.romankl.bitcoinvalue.data.async.BaseConversionEndpointAsyncTask;
import io.github.romankl.bitcoinvalue.data.model.ConversionOperation;
import io.github.romankl.bitcoinvalue.data.model.ConversionRepository;
import io.github.romankl.bitcoinvalue.ui.activity.SupportedCurrencyActivity;
import io.github.romankl.bitcoinvalue.util.SharedPrefsUtil;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PreferenceManager.setDefaultValues(this, R.xml.prefs_general, false);

        if (savedInstanceState == null) {
            OverViewFragment fragment = new OverViewFragment();
            fragment.setContext(this);
            getSupportFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.action_set_default_currency) {
            switchCurrency();
        }

        return super.onOptionsItemSelected(item);
    }

    private void switchCurrency() {
        startActivity(new Intent(this, SupportedCurrencyActivity.class));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    public static class OverViewFragment extends Fragment {
        public static final String CONVERSION_CURRENCY_KEY = "conversion_currency";
        public static final String CONVERSION_VALUE_KEY = "conversion_value";
        public static final String CONVERSION_DESCRIPTION_KEY = "conversion_description";
        public static final String CURRENT_CURRENCY_STATE_KEY = "current_currency_state";

        @InjectView(R.id.description)
        TextView mDescription;
        @InjectView(R.id.currency)
        TextView mCurrency;
        @InjectView(R.id.conversionValue)
        TextView mConversionValue;

        private String mCurrentCurrency;

        private Context context;

        public OverViewFragment() {
        }

        public void setContext(Context context) {
            this.context = context;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            ButterKnife.inject(this, rootView);

            if (savedInstanceState == null) {
                mCurrentCurrency = SharedPrefsUtil.getDefaultCurrency(getActivity());
                prepareUi();
            } else {
                mCurrentCurrency = savedInstanceState.getString(CURRENT_CURRENCY_STATE_KEY);

                mDescription.setText(savedInstanceState.getString(CONVERSION_DESCRIPTION_KEY));
                mCurrency.setText(savedInstanceState.getString(CONVERSION_CURRENCY_KEY));
                mConversionValue.setText(savedInstanceState.getString(CONVERSION_VALUE_KEY));
            }

            if (!mCurrentCurrency.equalsIgnoreCase(SharedPrefsUtil.getDefaultCurrency(getActivity()))) {
                prepareUi();
            }

            return rootView;
        }

        private void prepareUi() {
            if (SharedPrefsUtil.getAutoSync(context)) {
                synchronizeWithEndpoint();
            } else {
                loadDataFromCache();
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putString(CONVERSION_DESCRIPTION_KEY, mDescription.getText().toString());
            outState.putString(CONVERSION_VALUE_KEY, mConversionValue.getText().toString());
            outState.putString(CONVERSION_CURRENCY_KEY, mCurrency.getText().toString());
            outState.putString(CURRENT_CURRENCY_STATE_KEY, mCurrentCurrency);
        }

        private void loadDataFromCache() {
            new ConversionEndpointAsyncLoadFromDb(context).execute();
        }

        private void synchronizeWithEndpoint() {
            Ion.with(context).load("https://api.coinbase.com/v1/currencies/exchange_rates").asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            if (e == null) {
                                new ConversionEndpointAsyncConversionOperation(context, result).execute();
                            }
                        }
                    });
        }

        private class ConversionEndpointAsyncLoadFromDb extends BaseConversionEndpointAsyncTask {

            private ConversionEndpointAsyncLoadFromDb(final Context context) {
                super(context);
            }

            @Override
            protected Void doInBackground(final Void... params) {
                currency = SharedPrefsUtil.getDefaultCurrency(context);

                final ConversionRepository repository = new ConversionRepository(context);
                conversion = getConversionFromDb(repository);

                dateString = new DateTime().toString();

                repository.close();

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                updateUiWithValues(mCurrency, mConversionValue, mDescription);
            }
        }

        private class ConversionEndpointAsyncConversionOperation extends BaseConversionEndpointAsyncTask {
            private JsonObject object;

            private ConversionEndpointAsyncConversionOperation(Context context, JsonObject object) {
                super(context);
                this.object = object;
            }

            @Override
            protected Void doInBackground(Void... params) {
                new ConversionOperation(context, object).performConversionOperation();

                currency = SharedPrefsUtil.getDefaultCurrency(context);
                ConversionRepository repository = new ConversionRepository(context);

                if (SharedPrefsUtil.getTruncateTableBeforeSync(context))
                    repository.truncateTable();

                conversion = getConversionFromDb(repository);

                dateString = new DateTime().toString();
                SharedPrefsUtil.setLatestSync(context, dateString);

                repository.close();

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                updateUiWithValues(mCurrency, mConversionValue, mDescription);
            }
        }
    }
}