io.github.romankl.bitcoinvalue.ui.fragment.CurrencyListFragment.java Source code

Java tutorial

Introduction

Here is the source code for io.github.romankl.bitcoinvalue.ui.fragment.CurrencyListFragment.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.ui.fragment;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

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

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.github.romankl.bitcoinvalue.R;
import io.github.romankl.bitcoinvalue.data.model.Currency;
import io.github.romankl.bitcoinvalue.data.model.CurrencyRepository;
import io.github.romankl.bitcoinvalue.data.model.ModelBase;
import io.github.romankl.bitcoinvalue.ui.adapter.CurrencyAdapter;

public class CurrencyListFragment extends Fragment implements AdapterView.OnItemClickListener {
    @InjectView(android.R.id.list)
    ListView mListView;
    @InjectView(R.id.pullToRefresh)
    PtrClassicFrameLayout mPullToRefresh;

    private OnCurrencyInteractionListener mListener;

    public CurrencyListFragment() {
    }

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

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

        new DbListLoader().execute();

        mPullToRefresh.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                fetchNewSupportedCurrencies();
            }
        });

        mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        mListView.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnCurrencyInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mListener.onNewCurrencySelected(String.valueOf(id),
                ((Currency) mListView.getAdapter().getItem(position)).getShortName());
    }

    private void fetchNewSupportedCurrencies() {
        Ion.with(getActivity()).load("https://api.coinbase.com/v1/currencies").asJsonArray()
                .setCallback(new FutureCallback<JsonArray>() {
                    @Override
                    public void onCompleted(Exception e, JsonArray result) {
                        if (e == null) {
                            new EndPointFetching(result, mPullToRefresh).execute();
                        } else {
                            Log.d(this.getClass().toString(), e.toString());
                        }
                    }
                });
    }

    public interface OnCurrencyInteractionListener {
        public void onNewCurrencySelected(String id, String shortCurrencyName);
    }

    private class EndPointFetching extends AsyncTask<Void, Void, Void> {
        private JsonArray resultArray;
        private PtrClassicFrameLayout layout;

        private EndPointFetching(JsonArray resultArray, PtrClassicFrameLayout layout) {
            this.resultArray = resultArray;
            this.layout = layout;
        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... params) {
            CurrencyRepository repository = new CurrencyRepository(getActivity());

            repository.truncateTable();

            Currency currency;
            for (int i = 0; i < resultArray.size(); i++) {

                final JsonArray elements = ((JsonArray) resultArray).get(i).getAsJsonArray();
                currency = new Currency(elements.get(0).getAsString(), elements.get(1).getAsString());

                repository.insert(currency);
            }
            repository.close();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            new DbListLoader(layout).execute();
        }
    }

    private class DbListLoader extends AsyncTask<Void, Void, Void> {
        private List<ModelBase> list;
        private PtrClassicFrameLayout layout;

        public DbListLoader() {
        }

        public DbListLoader(PtrClassicFrameLayout layout) {
            this.layout = layout;
        }

        public void setLayout(PtrClassicFrameLayout layout) {

            this.layout = layout;
        }

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

        @Override
        protected Void doInBackground(Void... params) {
            CurrencyRepository repository = new CurrencyRepository(getActivity());
            list = repository.loadAll();
            repository.close();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            CurrencyAdapter adapter = new CurrencyAdapter(getActivity(), R.layout.single_item_currency_element,
                    list);
            mListView.setAdapter(adapter);

            if (layout != null)
                layout.refreshComplete();
        }
    }
}