de.aw.monma.actions.FragmentWPList.java Source code

Java tutorial

Introduction

Here is the source code for de.aw.monma.actions.FragmentWPList.java

Source

/*
 * MonMa: Eine freie Android-Application fuer die Verwaltung privater Finanzen
 *
 * Copyright [2015] [Alexander Winkler, 2373 Dahme/Germany]
 *
 * 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 de.aw.monma.actions;

import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;

import de.aw.awlib.adapters.AWItemListAdapter;
import de.aw.awlib.adapters.AWItemListAdapterTemplate;
import de.aw.awlib.fragments.AWFragment;
import de.aw.awlib.recyclerview.AWItemListRecyclerViewFragment;
import de.aw.awlib.recyclerview.AWLibViewHolder;
import de.aw.monma.BR;
import de.aw.monma.R;
import de.aw.monma.database.DBDefinition;
import de.aw.monma.databinding.WertpapierListItem;
import de.aw.monma.gv.GeschaeftsObjekt;
import de.aw.monma.gv.PartnerStammdaten;
import de.aw.monma.gv.WPKurs;
import de.aw.monma.monmamain.MonMaInterface;
import de.aw.monma.wertpapier.ActivityWertpapiere;
import de.aw.monma.wertpapier.FragmentWPPaketListe;
import de.aw.monma.wertpapier.FragmentWertpapierBuchungenListe;
import de.aw.monma.wertpapier.FragmentWertpapierKurseListe;
import de.aw.monma.wertpapier.dialoge.DialogKursaktualisierung;
import de.aw.monma.wertpapier.dialoge.DialogWPStamm;

/**
 * zeigt die Liste der Wertpapiere
 */
public class FragmentWPList extends AWItemListRecyclerViewFragment<WertpapierListItem>
        implements MonMaInterface, SearchView.OnQueryTextListener, PopupMenu.OnMenuItemClickListener,
        AWItemListAdapterTemplate.ItemGenerator<WertpapierListItem> {
    private static final String ONLYBESTAND = "ONLYBESTAND", SORTIEREN = "SORTIEREN";
    private final static DBDefinition tbd = DBDefinition.WPUebersichtView;
    private static final String[] projection = new String[] { _id, column_partnername, column_wpkenn, column_isin,
            column_bestand, column_amount, column_wptyp, column_beobachten };
    private final static String selection = column_partnername + " LIKE ? ";
    private static final String orderBy = column_partnername;
    @SuppressWarnings("FieldCanBeLocal")
    private static int itemLayout = R.layout.wpliste_item;
    private int indexID;
    private int indexName;
    private Cursor mCurser;
    private boolean onlyBestand = false, sortieren = false;
    private String[] selectionArgs = new String[] { "%%" };

    @Override
    public WertpapierListItem createItem(Cursor c) {
        return new WertpapierListItem(c);
    }

    @Override
    protected AWItemListAdapterTemplate<WertpapierListItem> createListAdapter() {
        AWItemListAdapter<WertpapierListItem> adapter = new AWItemListAdapter<WertpapierListItem>(this) {
            @Override
            protected long getID(@NonNull WertpapierListItem item) {
                return item.getID();
            }
        };
        adapter.setHasStableIds(true);
        return adapter;
    }

    @Override
    public LayoutManager getLayoutManager() {
        return new GridLayoutManager(getActivity(), maxRecyclerViewColumns());
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);
        startOrRestartLoader();
    }

    @Override
    public void onBindViewHolder(AWLibViewHolder holder, WertpapierListItem item, int position) {
        holder.setVariable(BR.wpuebersicht, item);
    }

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

    /**
     * In der ActionBar die SearchView initialisieren
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_wplist, menu);
        menu.findItem(R.id.menu_item_onlyBestand).setChecked(onlyBestand);
        menu.findItem(R.id.menu_item_sortieren).setChecked(sortieren);
        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_List_search));
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        searchView.setOnQueryTextListener(this);
        super.onCreateOptionsMenu(menu, inflater);
    }

    /**
     * Diverse Spaltenindizies ermitteln und merken. NoEntries-View ein-/ausblenden
     */
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        mCurser = cursor;
        indexID = mCurser.getColumnIndexOrThrow(_id);
        indexName = mCurser.getColumnIndexOrThrow(column_partnername);
        getAdapter().swap(cursor, this);
        super.onLoadFinished(loader, cursor);
    }

    /**
     * Wenn der Loader resettet wird, die Referenz auf den Cursor loeschen
     */
    @Override
    public void onLoaderReset(Loader<Cursor> p1) {
        mCurser = null;
        super.onLoaderReset(p1);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        boolean consumed = false;
        AWFragment f = null;
        Bundle extras = item.getIntent().getExtras();
        Long wpid = extras.getLong(WPID);
        String wpname = extras.getString(WPNAME);
        int mAccountID = extras.getInt(ACCOUNTID);
        switch (item.getItemId()) {
        case R.id.context_menu_item_wpKursAktualisieren:
            WPKurs kurs = new WPKurs();
            kurs.put(column_wpid, wpid);
            kurs.setWPName(wpname);
            DialogKursaktualisierung dialog = DialogKursaktualisierung.newInstance(kurs);
            dialog.show(getFragmentManager(), dialog.TAG);
            consumed = true;
            break;
        case R.id.context_menu_item_wpPaketeansehen:
            f = FragmentWPPaketListe.newInstance(mAccountID, wpid, new Bundle());
            wpname = extras.getString(WPNAME);
            setTitle(getString(R.string.Pakete) + " " + wpname);
            f.setArguments(extras);
            consumed = true;
            break;
        case R.id.context_menu_item_wpKurseBearbeiten:
            f = new FragmentWertpapierKurseListe();
            f.setArguments(extras);
            setTitle(R.string.tvKursFuerWertpapier);
            consumed = true;
            break;
        case R.id.context_menu_item_wpUmsaetze:
            f = FragmentWertpapierBuchungenListe.newInstance(mAccountID, wpid, wpname);
            consumed = true;
            break;
        case R.id.context_menu_item_wpErtraegeDetails:
            Intent intent = item.getIntent();
            intent.setClass(getActivity(), ActivityActions.class);
            intent.putExtra(ACTION, (Parcelable) Action.ShowWPDetails);
            startActivity(intent);
            consumed = true;
            break;
        default:
        }
        if (f != null) {
            replaceFragment(f);
        }
        return consumed;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_item_onlyBestand:
            onlyBestand = !onlyBestand;
            item.setChecked(onlyBestand);
            args.putBoolean(ONLYBESTAND, onlyBestand);
            startOrRestartLoader(layout, args);
            return true;
        case R.id.menu_item_sortieren:
            sortieren = !sortieren;
            item.setChecked(sortieren);
            String mOrderBy;
            if (sortieren) {
                mOrderBy = column_amount + " DESC ," + orderBy;
            } else {
                mOrderBy = orderBy;
            }
            args.putBoolean(SORTIEREN, sortieren);
            args.putString(ORDERBY, mOrderBy);
            startOrRestartLoader(layout, args);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Wird ein Wertpapier ueber das SearchWidget gesucht, wird bei jedem neuen Buchstaben die Liste
     * aktualisiert.
     *
     * @return immer true
     */
    @Override
    public boolean onQueryTextChange(String newText) {
        selectionArgs = new String[] { "%" + newText + "%" };
        args.putStringArray(SELECTIONARGS, selectionArgs);
        startOrRestartLoader(layout, args);
        return true;
    }

    /**
     * Wird ein Wertpapier ueber das SearchWidget gesucht, wird bei Click auf Oeffnen die Liste der
     * Buchungen angezeigt, wenn nur ganau ein WP angezeigt wird. Ansonsten wird nichts gemacht.
     *
     * @return immer true
     */
    @Override
    public boolean onQueryTextSubmit(String query) {
        if (mCurser != null && mCurser.getCount() == 1) {
            showWPBuchungen(mCurser.getLong(indexID), mCurser.getString(indexName));
        }
        return true;
    }

    /**
     * Bei Click wird das contextmenu gezeigt. In den jeweiligen extras sind folgende Informationen
     * enthalten: WPID, AMOUNT, WPNAME des gewaehlten Wertpapiers.
     */
    @Override
    public void onRecyclerItemClick(View view, int position, WertpapierListItem item) {
        super.onRecyclerItemClick(view, position, item);
        Intent intent = new Intent();
        intent.putExtra(WPID, item.getID());
        intent.putExtra(WPNAME, item.getWPName());
        intent.putExtra(ACCOUNTID, NOID);
        intent.putExtra(AMOUNT, item.getGewinn());
        PopupMenu popUpMenu = new PopupMenu(getActivity(), view);
        popUpMenu.inflate(R.menu.context_fragment_wpuebersicht);
        popUpMenu.inflate(R.menu.context_fragment_wpliste);
        Menu menu = popUpMenu.getMenu();
        for (int i = 0; i < menu.size(); i++) {
            menu.getItem(i).setIntent(intent);
        }
        popUpMenu.setOnMenuItemClickListener(this);
        popUpMenu.show();
    }

    /**
     * Bei LongClick wird das Wertpapier zur Bearbeitung angeboten.
     */
    @SuppressLint("MissingSuperCall")
    @Override
    public boolean onRecyclerItemLongClick(View view, int position, WertpapierListItem item) {
        try {
            PartnerStammdaten partner = new PartnerStammdaten(item.getID());
            DialogWPStamm d = DialogWPStamm.newInstance(partner);
            d.show(getFragmentManager(), d.getTAG());
        } catch (GeschaeftsObjekt.LineNotFoundException e) {
            //TODO Execption bearbeiten
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public void setCursorLoaderArguments(int p1, Bundle args) {
        String mSelection;
        if (onlyBestand) {
            mSelection = selection + " AND " + column_bestand + " > 100 ";
        } else {
            mSelection = selection;
        }
        args.putString(SELECTION, mSelection);
    }

    @Override
    protected void setInternalArguments(Bundle args) {
        super.setInternalArguments(args);
        args.putParcelable(DBDEFINITION, tbd);
        args.putInt(VIEWHOLDERLAYOUT, itemLayout);
        args.putStringArray(PROJECTION, projection);
        args.putString(SELECTION, selection);
        args.putStringArray(SELECTIONARGS, selectionArgs);
        args.putString(ORDERBY, orderBy);
        onlyBestand = args.getBoolean(ONLYBESTAND, true);
        sortieren = args.getBoolean(SORTIEREN, false);
    }

    /**
     * Zeigt die Buchungen zum selektierte WP. Kann entweder ueber die Suche erreicht werden (wenn
     * genau ein WP angezeigt wird) oder durch Click auf das WP.
     */
    private void showWPBuchungen(long wpid, String wpname) {
        Intent intent = new Intent(getActivity(), ActivityWertpapiere.class);
        intent.putExtra(ACTION, (Parcelable) Action.ShowBuchungen);
        intent.putExtra(WPID, wpid);
        intent.putExtra(WPNAME, wpname);
        startActivity(intent);
    }
}