cat.wuyingren.rorhelper.fragments.GameListFragment.java Source code

Java tutorial

Introduction

Here is the source code for cat.wuyingren.rorhelper.fragments.GameListFragment.java

Source

/** Copyright (c) 2014 Jordi Lpez <@wuyingren>
 *
 * MIT License:
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */
package cat.wuyingren.rorhelper.fragments;

/**
 * Created by wuyingren on 17/02/14.
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

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

import cat.wuyingren.rorhelper.R;
import cat.wuyingren.rorhelper.activities.MainActivity;
import cat.wuyingren.rorhelper.profiles.Game;
import cat.wuyingren.rorhelper.sql.GameDataSource;
import cat.wuyingren.rorhelper.utils.MultipleRowAdapter;

/**
 * A placeholder fragment containing a simple view.
 */
public class GameListFragment extends ListFragment {

    private GameDataSource dataSource;
    private MultipleRowAdapter adapter;
    private List<Game> values;

    private ProgressDialog pDialog;

    /* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface GameListFragmentListener {
        void onGameListItemClick(long id);
        //public void onMultipleItemsDeletion();
    }

    // Use this instance of the interface to deliver action events
    GameListFragmentListener mListener;

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    /* public static GameListFragment newInstance(int sectionNumber) {
    GameListFragment fragment = new GameListFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
     }*/

    public GameListFragment() {

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        dataSource = new GameDataSource(getActivity());
        dataSource.open();

        values = dataSource.getAllGames();

        adapter = new MultipleRowAdapter(getActivity(), values);

        setListAdapter(adapter);

        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(new ListView.MultiChoiceModeListener() {

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Here you can do something when items are selected/de-selected,
                // such as update the title in the CAB
                //mode.setTag();
                int selectionColor = getResources().getColor(R.color.colorPrimary);
                Log.w("TAG", "onItemCheckedStateChanged() " + checked + " " + position);
                mode.setSubtitle(listView.getCheckedItemCount() + " selected");
                if (checked) {
                    listView.getChildAt(position).setBackgroundColor(selectionColor);
                } else {
                    listView.getChildAt(position)
                            .setBackgroundColor(getResources().getColor(android.R.color.transparent));
                }
            }

            @Override
            public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
                // Inflate the menu for the CAB

                Log.w("TAG", "onCreateActionMode");
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.menu_context, menu);
                mode.setTitle(getString(R.string.action_choose));
                return true;
            }

            @Override
            public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
                // Here you can perform updates to the CAB due to
                // an invalidate() request
                return false;
            }

            @Override
            public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
                // Respond to clicks on the actions in the CAB

                switch (item.getItemId()) {
                case R.id.action_delete:
                    deleteItems(listView.getCheckedItemPositions());
                    mode.finish();
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public void onDestroyActionMode(android.view.ActionMode mode) {
                // Here you can make any necessary updates to the activity when
                // the CAB is removed. By default, selected items are deselected/unchecked.

                SparseBooleanArray checked = listView.getCheckedItemPositions();
                for (int i = 0; i < listView.getAdapter().getCount(); i++) {
                    if (checked.get(i)) {
                        listView.getChildAt(i)
                                .setBackgroundColor(getResources().getColor(android.R.color.transparent));
                    }
                }
            }

        });
        // dataSource.close();
    }

    private void deleteItems(SparseBooleanArray positions) {

        SparseBooleanArray chkItems = positions;
        //ArrayList<Game> selItems = new ArrayList<Game>();
        ArrayList<Long> selItems = new ArrayList<Long>();
        for (int i = 0; i < chkItems.size(); i++) {
            int position = chkItems.keyAt(i);
            if (chkItems.valueAt(i)) {
                selItems.add(adapter.getItem(position).getId());
            }
        }
        DeleteGameTask task = new DeleteGameTask();
        Long[] longs = new Long[selItems.size()];
        longs = selItems.toArray(longs);
        task.execute(longs);

        /*
                for(Game g:selItems) {
        dataSource.deleteGame(g);
        mListener.onMultipleItemsDeletion();
        //dataSource.deleteSchedule(context, s);
        //updateDB();
                }*/
    }

    private class DeleteGameTask extends AsyncTask<Long, Long, Void> {

        @Override
        protected Void doInBackground(Long... longs) {
            for (long l : longs) {
                dataSource.deleteGameById(l);
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.getContext());
            pDialog.setMessage(getString(R.string.pDialog_game_deleting));
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            refresh();
            pDialog.setMessage(getString(R.string.pDialog_game_done));
            pDialog.dismiss();
            //mListener.onMultipleItemsDeletion();
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        /*((MainActivity) activity).onSectionAttached(
            getArguments().getInt(ARG_SECTION_NUMBER));*/
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (GameListFragmentListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString() + " must implement ScenarioDialogListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        mListener.onGameListItemClick(adapter.getItem(position).getId());
    }

    public void refresh() {

        // Refresh values
        values = dataSource.getAllGames();
        adapter.clear();
        for (Game value : values) {
            adapter.add(value);
        }
        // adapter.addAll(values);  <- Not working on 2.x
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }
}