com.bydavy.card.receipts.fragments.ReceiptAddFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.bydavy.card.receipts.fragments.ReceiptAddFragment.java

Source

/*
 * Copyright (C) 2012 Davy Leggieri
 * 
 * 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 2
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package com.bydavy.card.receipts.fragments;

import java.util.Calendar;

import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.bydavy.card.receipts.R;
import com.bydavy.card.receipts.ShopSuggestionAdapter;
import com.bydavy.card.receipts.providers.Receipts;
import com.bydavy.card.receipts.providers.ReceiptsHelper;
import com.bydavy.card.receipts.utils.CurrencyFormat;
import com.bydavy.card.receipts.utils.LogHelper;
import com.bydavy.card.receipts.utils.LogHelper.ErrorID;
import com.bydavy.card.receipts.utils.MyDateFormat;

public class ReceiptAddFragment extends SherlockFragment {
    /** Change first statement of if condition to enable class debug **/
    private static final boolean DEBUG = LogHelper.DEBUG ? false : LogHelper.DEFAULT_DEBUG;
    private static final String DEBUG_PREFIX = ReceiptAddFragment.class.getName();

    public static final String ARG_RECEIPT_ID = "receiptId";
    public static final String ARG_MODE = "mode";

    private static final String STATE_SHOP = "addReceiptShop";
    private static final String STATE_DATE = "addReceiptDate";
    private static final String STATE_NOTE = "addReceiptNote";
    private static final String STATE_TOTAL = "addReceiptTotal";

    private static final String DATE_PICKER_DIALOG_FRAGMENT_TAG = "dateFrag";

    private MyDateFormat mDateFormat;
    private CurrencyFormat mCurrencyFormat;
    private final Calendar mCalendar = Calendar.getInstance();

    private AutoCompleteTextView mViewShop;
    private TextView mViewDate;
    private EditText mViewNote;
    private EditText mViewTotal;

    public static ReceiptAddFragment newInstance() {
        return new ReceiptAddFragment();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mDateFormat = MyDateFormat.getDateFormat(activity);
        mCurrencyFormat = CurrencyFormat.getCurrencyFormat(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_receipt_edit, null);
        mViewShop = (AutoCompleteTextView) view.findViewById(R.id.shop);
        mViewShop.setAdapter(new ShopSuggestionAdapter(getActivity(), mViewShop));

        mViewDate = (TextView) view.findViewById(R.id.date);
        mViewNote = (EditText) view.findViewById(R.id.note);
        mViewTotal = (EditText) view.findViewById(R.id.total);
        final TextView viewCurrency = (TextView) view.findViewById(R.id.currency);
        viewCurrency.setText(mCurrencyFormat.getCurrencySymbol());
        mViewDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
            }
        });
        return view;
    };

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(STATE_SHOP, mViewShop.getText().toString());
        outState.putLong(STATE_DATE, mCalendar.getTimeInMillis());
        outState.putString(STATE_NOTE, STATE_NOTE);
        try {
            outState.putFloat(STATE_TOTAL, Float.valueOf(mViewTotal.getText().toString()));
        } catch (final NumberFormatException e) {
            /* Nothing */
        }
        super.onSaveInstanceState(outState);
    }

    private void refreshView(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            mViewShop.setText("");
            mViewNote.setText("");
            mViewTotal.setText("");
        } else {
            mCalendar.setTimeInMillis(savedInstanceState.getLong(STATE_DATE));
            mViewShop.setText(savedInstanceState.getString(STATE_SHOP));
            mViewNote.setText(savedInstanceState.getString(STATE_NOTE));
            mViewTotal.setText(savedInstanceState.getString(STATE_TOTAL));
        }
        refreshDate();
    }

    private void refreshDate() {
        mViewDate.setText(mDateFormat.format(mCalendar.getTime()));
    }

    private void showDatePickerDialog() {
        final FragmentTransaction ft = getFragmentManager().beginTransaction();
        final Fragment prev = getFragmentManager().findFragmentByTag(DATE_PICKER_DIALOG_FRAGMENT_TAG);
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        final DatePickerDialogFragment dialog = DatePickerDialogFragment.newInstance(mCalendar.get(Calendar.YEAR),
                mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
        dialog.show(ft, DATE_PICKER_DIALOG_FRAGMENT_TAG);
    }

    public void setDate(int year, int monthOfYear, int dayOfMonth) {
        mCalendar.set(year, monthOfYear, dayOfMonth);
        refreshDate();
    }

    public boolean save() {
        if (!isFieldsValid()) {
            return false;
        }
        return insertReceiptInDB();
    }

    private boolean isFieldsValid() {
        final String shop = mViewShop.getText().toString();
        if (TextUtils.isEmpty(shop)) {
            Toast.makeText(getActivity(), getResources().getString(R.string.fragment_receipt_edit__set_shop_msg),
                    Toast.LENGTH_LONG).show();
            return false;
        }
        final String tmpTotal = mViewTotal.getText().toString();
        if (TextUtils.isEmpty(tmpTotal)) {
            Toast.makeText(getActivity(), getResources().getString(R.string.fragment_receipt_edit__set_total_msg),
                    Toast.LENGTH_LONG).show();
            return false;
        }
        try {
            Float.parseFloat(tmpTotal);
        } catch (final NumberFormatException e) {
            Toast.makeText(getActivity(), getResources().getString(R.string.fragment_receipt_edit__set_total_msg),
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    private boolean insertReceiptInDB() {
        final String shop = mViewShop.getText().toString();
        final String tmpTotal = mViewTotal.getText().toString();
        float total = 0;
        try {
            total = Float.parseFloat(tmpTotal);
        } catch (final NumberFormatException e) {
            /* Nothing */
        }
        // Not required fields
        final String description = mViewNote.getText().toString();
        final long date = mCalendar.getTimeInMillis() / 1000;

        final ContentValues receipt = ReceiptsHelper.toContentValues(shop, description, date, total, false, null);
        try {
            getActivity().getContentResolver().insert(Receipts.CONTENT_URI, receipt);
        } catch (final Exception e) {
            LogHelper.e(ErrorID.CONTENT_PROVIDER, "Cannot insert receipt in db: " + e, e);
            // TODO inform the user and ask if we can send a debug info to dev'
            return false;
        }
        return true;
    }
}