org.kei.android.phone.mangastore.AppFragment.java Source code

Java tutorial

Introduction

Here is the source code for org.kei.android.phone.mangastore.AppFragment.java

Source

package org.kei.android.phone.mangastore;

import static org.kei.android.phone.mangastore.utils.Config.CFG;

import java.util.ArrayList;
import java.util.List;

import org.kei.android.atk.utils.Tools;
import org.kei.android.phone.mangastore.R;
import org.kei.android.phone.mangastore.dialog.DialogHelper;
import org.kei.android.phone.mangastore.dialog.action.DialogActionAdd;
import org.kei.android.phone.mangastore.http.HttpTaskFetch;
import org.kei.android.phone.mangastore.http.HttpTaskListener;
import org.kei.android.phone.mangastore.list.ListIndexer;
import org.kei.android.phone.mangastore.list.ListMultiChoice;
import org.kei.android.phone.mangastore.list.MangaArrayAdapter;
import org.kei.android.phone.mangastore.list.MangaModel;
import org.kei.android.phone.mangastore.list.MangaModel.MangaType;
import org.kei.android.phone.mangastore.list.MangaModel.StatusType;
import org.kei.android.phone.mangastore.utils.Config;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *******************************************************************************
 * @file AppFragment.java
 * @author Keidan
 * @date 24/12/2015
 * @par Project MangaStore
 *
 * @par Copyright 2015 Keidan, all right reserved
 *
 *      This software is distributed in the hope that it will be useful, but
 *      WITHOUT ANY WARRANTY.
 *
 *      License summary : You can modify and redistribute the sources code and
 *      binaries. You can send me the bug-fix
 *
 *      Term of the license in in the file license.txt.
 *
 *******************************************************************************
 */
@SuppressLint("ClickableViewAccessibility")
public class AppFragment extends Fragment
        implements OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, HttpTaskListener {
    private ListView listMangas = null;
    private MangaArrayAdapter adapter = null;
    private int layout_id = 0;
    private GestureDetector gestureDetector = null;
    private ListIndexer indexer = null;
    private ListMultiChoice multiChoice = null;
    private String name = null;
    private boolean cancel = false;
    private SwipeRefreshLayout swipeRefreshLayout = null;

    public AppFragment() {
    }

    public void initialize(final String name, final int layout_id, final MangaArrayAdapter adapter,
            final ListIndexer indexer) {
        this.name = name;
        this.adapter = adapter;
        this.layout_id = layout_id;
        this.indexer = indexer;
    }

    public static MangaArrayAdapter allocAdapter(final Context context) {
        return new MangaArrayAdapter(context, R.layout.row_listmanga, new ArrayList<MangaModel>());
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
            final Bundle savedInstanceState) {
        final ViewGroup rootView = (ViewGroup) inflater.inflate(layout_id, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        listMangas = (ListView) rootView.findViewById(R.id.list);
        listMangas.setAdapter(adapter);
        indexer.initialize(rootView);
        multiChoice = new ListMultiChoice(((MangaStorePagerActivity) getActivity()), listMangas);
        gestureDetector = new GestureDetector(rootView.getContext(), indexer);
        listMangas.setOnItemClickListener(this);
        listMangas.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
        listMangas.setMultiChoiceModeListener(multiChoice);
        rootView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(final View v, final MotionEvent event) {
                if (gestureDetector.onTouchEvent(event))
                    return true;
                else
                    return false;
            }
        });
        swipeRefreshLayout.setOnRefreshListener(this);
        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                fetch();
            }
        });

        return rootView;
    }

    public void onPause() {
        cancel();
        super.onPause();
    }

    public void cancel() {
        cancel = true;
    }

    public void refresh() {
        cancel = false;
        new Thread() {
            public void run() {
                while (!cancel) {
                    if (isAdded()) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                indexer.forceReload();
                            }
                        });
                        break;
                    } else
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                        }
                }
            }
        }.start();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final MangaModel model = adapter.getItem(position);
        MangaStorePagerActivity mspa = (MangaStorePagerActivity) getActivity();
        int color = mspa.getCurrentColor();
        DialogHelper
                .showCustomDialog(view.getContext(), R.layout.dialog_add_manga, getString(R.string.manga), color,
                        new DialogActionAdd(view.getContext(),
                                CFG.get(Config.KEY_PAGER_CURRENT_TAB, 0) == 0 ? true : false, true, color, mspa),
                        model);
    }

    /**
     * This method is called when swipe refresh is pulled down
     */
    @Override
    public void onRefresh() {
        fetch();
    }

    public void fetch() {
        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(true);
        new HttpTaskFetch<AppFragment>(this).execute(CFG.get(Config.KEY_WEB_URL, ""),
                CFG.get(Config.KEY_WEB_NAME, ""), CFG.get(Config.KEY_WEB_PWD, ""));
    }

    @Override
    public void onTaskResponse(JSONArray array) {
        if (array != null)
            convertFromJSON(array);
    }

    @Override
    public void onTaskError(Throwable t) {
        Tools.toast(getActivity(), R.drawable.ic_launcher, "Error: " + t.getMessage());
    }

    private void convertFromJSON(JSONArray response) {
        boolean aborted = true;
        boolean finished = true;
        boolean inprogress = true;
        final int position = CFG.get(Config.KEY_PAGER_CURRENT_TAB, 0);
        final MangaType selectedType = MangaType.getType(position);
        if (position == MangaStorePagerActivity.POSITION_MANGAS) {
            aborted = CFG.get(Config.KEY_SHOW_MANGAS_ABORTED, true);
            finished = CFG.get(Config.KEY_SHOW_MANGAS_FINISHED, true);
            inprogress = CFG.get(Config.KEY_SHOW_MANGAS_INPROGRESS, true);
        } else if (position == MangaStorePagerActivity.POSITION_ANIMES) {
            aborted = CFG.get(Config.KEY_SHOW_ANIMES_ABORTED, true);
            finished = CFG.get(Config.KEY_SHOW_ANIMES_FINISHED, true);
            inprogress = CFG.get(Config.KEY_SHOW_ANIMES_INPROGRESS, true);
        } else if (position == MangaStorePagerActivity.POSITION_MOVIES) {
            aborted = CFG.get(Config.KEY_SHOW_MOVIES_ABORTED, true);
            finished = CFG.get(Config.KEY_SHOW_MOVIES_FINISHED, true);
            inprogress = CFG.get(Config.KEY_SHOW_MOVIES_INPROGRESS, true);
        } else if (position == MangaStorePagerActivity.POSITION_OAV) {
            aborted = CFG.get(Config.KEY_SHOW_OAV_ABORTED, true);
            finished = CFG.get(Config.KEY_SHOW_OAV_FINISHED, true);
            inprogress = CFG.get(Config.KEY_SHOW_OAV_INPROGRESS, true);
        }
        if (response.length() > 0) {
            List<MangaModel> mangaList = new ArrayList<MangaModel>();
            // looping through json and adding to movies list
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject mObj = response.getJSONObject(i);
                    MangaType type = MangaType.getType(mObj.getInt("type"));
                    StatusType status = StatusType.getType(mObj.getInt("status"));
                    if (type != selectedType)
                        continue;
                    if (!aborted && status == StatusType.ABORTED)
                        continue;
                    if (!finished && status == StatusType.FINISHED)
                        continue;
                    if (!inprogress && status == StatusType.INPROGRESS)
                        continue;
                    int id = mObj.getInt("id");
                    int year = mObj.getInt("year");
                    String label = mObj.getString("name");
                    int volume = mObj.getInt("number");
                    MangaModel m = new MangaModel(id, type, label, year, volume, status);
                    mangaList.add(0, m);
                } catch (JSONException e) {
                    Tools.toast(getActivity(), R.drawable.ic_launcher, "JSON Parsing error: " + e.getMessage());
                    e.printStackTrace();
                    mangaList.clear();
                    break;
                }
            }
            if (!mangaList.isEmpty()) {
                adapter.clear();
                adapter.addAll(mangaList);
                adapter.sort();
                if (isAdded())
                    indexer.forceReload();
                else
                    refresh();
            }
        }
        // stopping swipe refresh
        swipeRefreshLayout.setRefreshing(false);
    }

    public String getName() {
        return name;
    }

}