palamarchuk.smartlife.app.fragments.ProfileFragment.java Source code

Java tutorial

Introduction

Here is the source code for palamarchuk.smartlife.app.fragments.ProfileFragment.java

Source

package palamarchuk.smartlife.app.fragments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import palamarchuk.smartlife.app.ActivityInitialNavigation;
import palamarchuk.smartlife.app.FragmentHolderActivity;
import palamarchuk.smartlife.app.R;
import palamarchuk.smartlife.app.RegisterActivity;
import palamarchuk.smartlife.app.UserInfo;
import palamarchuk.smartlife.app.dialogs.DialogAttachCard;
import palamarchuk.smartlife.app.dialogs.DialogUserCards;
import palamarchuk.smartlife.app.dialogs.GiveBonuses;
import parser.QueryMaster;
import parser.ServerRequest;

public class ProfileFragment extends Fragment implements View.OnClickListener, QueryMaster.OnCompleteListener {

    private Activity parentActivity;
    private GiveBonuses giveBonuses;
    private TextView userPoints;

    private DialogAttachCard dialogAttachCard;

    private DialogAttachCard.ObtainResultListener cardNumberResult = new DialogAttachCard.ObtainResultListener() {
        @Override
        public void obtainResult(String cardNumber, String pinCode) {
            if (!cardNumber.isEmpty() && !pinCode.isEmpty()) {
                attachCardQuery(cardNumber, pinCode);
            }
        }
    };

    public static ProfileFragment newInstance(UserInfo userInfo) {
        ProfileFragment profileFragment = new ProfileFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(UserInfo.PARCELABLE_KEY, userInfo);
        profileFragment.setArguments(bundle);
        return profileFragment;
    }

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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        ((FragmentHolderActivity) parentActivity).updateTitle("");

        dialogAttachCard = new DialogAttachCard(getActivity(), true);
        dialogAttachCard.setObtainResultListener(cardNumberResult);

        View rootView = inflater.inflate(R.layout.profile, null);

        Bundle bundle = getArguments();
        UserInfo userInfo = bundle.getParcelable(UserInfo.PARCELABLE_KEY);

        ((TextView) rootView.findViewById(R.id.profile_name))
                .setText(userInfo.getFirst_name() + " " + userInfo.getLastName());
        ((TextView) rootView.findViewById(R.id.profile_email)).setText(userInfo.getEmail());
        ((TextView) rootView.findViewById(R.id.profile_phone)).setText(userInfo.getPhone());
        ((TextView) rootView.findViewById(R.id.profile_birth_date)).setText(userInfo.getBirthdate());
        userPoints = (TextView) rootView.findViewById(R.id.profile_points);
        userPoints.setText(userInfo.getPoints());

        rootView.findViewById(R.id.profile_setting).setOnClickListener(this);
        rootView.findViewById(R.id.profile_feedback).setOnClickListener(this);
        rootView.findViewById(R.id.profile_edit_favorite).setOnClickListener(this);
        rootView.findViewById(R.id.profile_history).setOnClickListener(this);
        rootView.findViewById(R.id.profile_rules).setOnClickListener(this);
        rootView.findViewById(R.id.profileGiveBonuses).setOnClickListener(this);
        rootView.findViewById(R.id.profileReopenInitialNavigation).setOnClickListener(this);
        rootView.findViewById(R.id.profileShowMyCards).setOnClickListener(this);

        rootView.findViewById(R.id.profileAttachCard).setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.profile_setting:
            setting();
            break;
        case R.id.profile_feedback:
            feedback();
            break;
        case R.id.profile_edit_favorite:
            editFavorite();
            break;
        case R.id.profile_history:
            clickHistory();
            break;
        case R.id.profile_rules:
            RegisterActivity.openUrl(parentActivity, ServerRequest.LICENSE);
            break;
        case R.id.profileGiveBonuses:
            /**
             * give bonuses listener
             * {@link #complete(String)}
             * {@link #error(int)}
             */
            giveBonuses = new GiveBonuses(getActivity(), this,
                    ((FragmentHolderActivity) getActivity()).getDeviceToken());
            giveBonuses.show();
            break;
        case R.id.profileReopenInitialNavigation:
            startActivity(new Intent(getActivity(), ActivityInitialNavigation.class));
            break;
        case R.id.profileAttachCard:

            UserInfo userInfo = ((FragmentHolderActivity) parentActivity).userInfo;
            dialogAttachCard.show();

            //                if (userInfo.getCard_number() == null || userInfo.getCard_number().isEmpty()) {
            //
            //                } else {
            //                    QueryMaster.toast(getActivity(), R.string.card_already_attached);
            //                }

            break;
        case R.id.profileShowMyCards:
            new DialogUserCards(getActivity()).show();
            break;
        }
    }

    private void setting() {
        ((FragmentHolderActivity) parentActivity).addFragment(Setting.newInstance());
    }

    private void feedback() {
        Intent sendIntent;
        sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "support@smartlife.com.kz" });
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
        sendIntent.putExtra(Intent.EXTRA_TEXT, "");
        sendIntent.setType("image/jpeg");

        try {
            startActivity(Intent.createChooser(sendIntent, "Send Mail"));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(parentActivity, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }
    }

    private void editFavorite() {
        ((FragmentHolderActivity) parentActivity)
                .addFragment(EditFavorite.newInstance(FragmentHolderActivity.getDeviceToken()));
    }

    private void clickHistory() {
        ((FragmentHolderActivity) parentActivity).addFragment(FragmentHistoryViewPager.instance());
        //        ((FragmentHolderActivity) parentActivity).addFragment(History.newInstance());
    }

    @Override
    public void complete(String serverResponse) {
        try {
            JSONObject json = new JSONObject(serverResponse);
            QueryMaster.toast(getActivity(), json.has("message") ? json.getString("message") : json.toString());

            String bonusCount = giveBonuses.bonusCount;
            giveBonuses = null;

            ((FragmentHolderActivity) getActivity()).userInfo.minusPoints(bonusCount);
            FragmentHelper.updateFragment(getFragmentManager());
        } catch (JSONException e) {
            e.printStackTrace();
            QueryMaster.alert(getActivity(), QueryMaster.ERROR_MESSAGE);
        }
    }

    @Override
    public void error(int errorCode) {
        QueryMaster.alert(getActivity(), QueryMaster.ERROR_MESSAGE);
    }

    private void updateUserInfo() {
        UserInfo info = ((FragmentHolderActivity) parentActivity).userInfo;

        String url = ServerRequest.GET_USER_INFO + info.getId() + "?token="
                + ((FragmentHolderActivity) parentActivity).getDeviceToken();

        QueryMaster update = new QueryMaster(parentActivity, url, QueryMaster.QUERY_GET);
        update.setOnCompleteListener(updateUserInfo);
        update.start();
    }

    private QueryMaster.OnCompleteListener updateUserInfo = new QueryMaster.OnCompleteListener() {
        @Override
        public void complete(String serverResponse) {
            try {
                JSONObject json = new JSONObject(serverResponse);
                if (QueryMaster.isSuccess(json)) {
                    ((FragmentHolderActivity) parentActivity).userInfo = new UserInfo(json.getJSONObject("data"));

                    userPoints.setText(((FragmentHolderActivity) parentActivity).userInfo.getPoints());

                }
            } catch (JSONException e) {
                e.printStackTrace();
                QueryMaster.alert(parentActivity, QueryMaster.SERVER_RETURN_INVALID_DATA);
            }
        }

        @Override
        public void error(int errorCode) {
            QueryMaster.alert(parentActivity, QueryMaster.ERROR_MESSAGE);
        }
    };

    private void attachCardQuery(String cardNumber, String cardPin) {

        final QueryMaster.OnCompleteListener onCompleteListener = new QueryMaster.OnCompleteListener() {
            @Override
            public void complete(String serverResponse) {
                //                QueryMaster.alert(getActivity(), serverResponse);
                try {
                    JSONObject json = new JSONObject(serverResponse);
                    if (QueryMaster.isSuccess(json)) {
                        FragmentHelper.updateFragment(getFragmentManager());

                        QueryMaster.alert(getActivity(), R.string.bonuses_was_added_from_card);

                    } else {
                        QueryMaster.toast(getActivity(), json.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    QueryMaster.alert(getActivity(), QueryMaster.SERVER_RETURN_INVALID_DATA);
                }
            }

            @Override
            public void error(int errorCode) {
                QueryMaster.alert(getActivity(), QueryMaster.ERROR_MESSAGE);
            }
        };

        MultipartEntity entity = new MultipartEntity();

        try {
            entity.addPart("card_number", new StringBody(cardNumber));
            entity.addPart("pin", new StringBody(cardPin));
            entity.addPart("token", new StringBody(((FragmentHolderActivity) getActivity()).getDeviceToken()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        QueryMaster queryMaster = new QueryMaster(getActivity(), ServerRequest.ATTACH_CARD, QueryMaster.QUERY_POST,
                entity);

        queryMaster.setProgressDialog();
        queryMaster.setOnCompleteListener(onCompleteListener);

        queryMaster.start();
    }

}