net.jongrakko.zipsuri.fragment.ExpertModifyFragment.java Source code

Java tutorial

Introduction

Here is the source code for net.jongrakko.zipsuri.fragment.ExpertModifyFragment.java

Source

package net.jongrakko.zipsuri.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.Switch;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import net.jongrakko.zipsuri.R;
import net.jongrakko.zipsuri.ZipsuriApplication;
import net.jongrakko.zipsuri.activity.RegisterExpertRegionActivity;
import net.jongrakko.zipsuri.manager.ProgressManger;
import net.jongrakko.zipsuri.manager.ServerManager;
import net.jongrakko.zipsuri.model.AddressModel;
import net.jongrakko.zipsuri.model.AuthModel;
import net.jongrakko.zipsuri.model.ExpertModel;
import net.jongrakko.zipsuri.model.PostModel;
import net.jongrakko.zipsuri.model.ReviewModel;
import net.jongrakko.zipsuri.model.UserModel;
import net.jongrakko.zipsuri.view.CheckableButton;

import java.util.List;

public class ExpertModifyFragment extends Fragment implements CompoundButton.OnCheckedChangeListener,
        OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMapClickListener {
    private static final int MY_LOCATION_REQUEST_CODE = 102;
    private static final int SELECT_CITY_REQUEST_CODE = 101;
    private CheckableButton[] btns;
    private int[] licenseButtonIds = { R.id.buttonLicense0, R.id.buttonLicense1, R.id.buttonLicense2,
            R.id.buttonLicense3, R.id.buttonLicense4, R.id.buttonLicense5, R.id.buttonLicense6, R.id.buttonLicense7,
            R.id.buttonLicense8, R.id.buttonLicense9, R.id.buttonLicense10, R.id.buttonLicense11,
            R.id.buttonLicense12, R.id.buttonLicense13, R.id.buttonLicense14, R.id.buttonLicense15 };
    private ImageView mImageViewLeft, mImageViewRight;
    private GoogleMap mGoogleMap;
    private AddressModel uploadAddressModel;

    View mRegisterView;
    Button mDuplicateCheckBtn, mAuthSendBtn, mAuthCheckBtn, mDoneBtn;
    ImageButton mBackBtn;
    EditText mNameEdit, mIdEdit, mPhoneEdit, mCodeEdit, mPasswordEdit, mPasswordConfirmEdit, mDescription;
    Switch mPushAllowSwitch;
    ReviewListAdapter mReviewListAdapter;
    List<ReviewModel> mReviewModels;

    boolean mIsIdChecked = false;
    boolean mIsAuthed = false;
    View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_expert_modify, container, false);

        setLayout();
        setMapView();

        mDuplicateCheckBtn.setOnClickListener(mOnClickListener);
        mAuthSendBtn.setOnClickListener(mOnClickListener);
        mAuthCheckBtn.setOnClickListener(mOnClickListener);
        mDoneBtn.setOnClickListener(mOnClickListener);
        mBackBtn.setOnClickListener(mOnClickListener);
        mImageViewLeft = (ImageView) rootView.findViewById(R.id.imageViewLeft);
        mImageViewRight = (ImageView) rootView.findViewById(R.id.imageViewRight);
        mImageViewLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ReviewModel rm = mReviewModels.get(mReviewModels.size() - 1);
                mReviewModels.remove(rm);
                mReviewModels.add(0, rm);
                mReviewListAdapter.notifyDataSetChanged();
            }
        });
        mImageViewRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mReviewModels.size() > 1) {
                    ReviewModel rm = mReviewModels.get(1);
                    mReviewModels.remove(rm);
                    mReviewModels.add(0, rm);
                    mReviewListAdapter.notifyDataSetChanged();
                }
            }
        });
        return rootView;
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.done:
                onDoneClick();
                break;
            case R.id.check_duplicate:
                onDuplicateCheckClick();
                break;
            case R.id.send_code:
                onAuthSendClick();
                break;
            case R.id.code_check:
                onAuthCheckClick();
                break;
            case R.id.ib_back:
                DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
                drawer.openDrawer(GravityCompat.START);
                break;

            }
        }

        private void onDuplicateCheckClick() {
            if (isEmpty(mIdEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_id_empty));
                return;
            }
            UserModel userModel = new UserModel();
            userModel.setUserId(mIdEdit.getText().toString());

            ServerManager.existUser(new ServerManager.OnServerListener<Void>() {
                @Override
                protected void onSuccess(Void data) {
                    ProgressManger.showToast("   ?.");
                    mIsIdChecked = true;
                }
            }, userModel);

        }

        private void onAuthSendClick() {
            if (isEmpty(mPhoneEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_phone_empty));
                return;
            }

            final String number = mPhoneEdit.getText().toString();

            if (!isProperNumber(number)) {
                ProgressManger.showToast(getString(R.string.register_toast_wrong_number));
                return;
            }

            AuthModel authModel = new AuthModel();
            authModel.setPhone(mPhoneEdit.getText().toString());
            ServerManager.sendAuth(new ServerManager.OnServerListener<Void>(getContext()) {
                @Override
                protected void onSuccess(Void data) {
                    ProgressManger.showToast(" .");
                }
            }, authModel);

        }

        private void onAuthCheckClick() {
            if (isEmpty(mCodeEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_code_empty));
                return;
            } else if (isEmpty(mPhoneEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_wrong_number));
                return;
            } else if (!mIsIdChecked) {
                ProgressManger.showToast(getString(R.string.register_toast_check_id));
                return;
            }

            AuthModel authModel = new AuthModel();
            authModel.setPhone(mPhoneEdit.getText().toString());
            authModel.setCode(mCodeEdit.getText().toString());

            ServerManager.checkAuth(new ServerManager.OnServerListener<Void>(getContext()) {
                @Override
                protected void onSuccess(Void data) {
                    ProgressManger.showToast(getString(R.string.register_toast_authed));
                    mPhoneEdit.setEnabled(false);
                    mIdEdit.setEnabled(false);
                    mCodeEdit.setEnabled(false);

                    mAuthSendBtn.setEnabled(false);
                    mAuthCheckBtn.setEnabled(false);

                    mIsAuthed = true;
                }

            }, authModel);

        }

        private void onDoneClick() {
            //  EditText  
            if (isEmpty(mNameEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_name_empty));
                return;
            } else if (isEmpty(mIdEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_id_empty));
                return;
            } else if (isEmpty(mPhoneEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_phone_empty));
                return;
            } else if (isEmpty(mPasswordEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_password_empty));
                return;
            } else if (isEmpty(mPasswordConfirmEdit)) {
                ProgressManger.showToast(getString(R.string.register_toast_password_confirm_empty));
                return;
            }

            // ? ? 

            if (!mPasswordEdit.getText().toString().equals(mPasswordConfirmEdit.getText().toString())) {
                ProgressManger.showToast(getString(R.string.register_toast_password_mismatch));
                return;
            }

            //  ? 
            if (uploadAddressModel == null) {
                ProgressManger.showToast(getString(R.string.register_toast_address_empty));
                return;
            }

            // ? ? 

            if (getLicense() == 0) {
                ProgressManger.showToast(" ? 1 ?? ?");
                return;
            }
            UserModel tmp = ZipsuriApplication.getUserModel();
            if (!tmp.getPhone().equals(mPhoneEdit.getText().toString())
                    && !tmp.getPasswd().equals(mPasswordEdit.getText().toString())) {
                ProgressManger.showToast(
                        "  ?  ? ?  .");
                return;
            }

            ExpertModel model = new ExpertModel();
            model.setName(mNameEdit.getText().toString());
            model.setUserId(mIdEdit.getText().toString());
            model.setPhone(mPhoneEdit.getText().toString());
            model.setPasswd(mPasswordEdit.getText().toString());
            model.setIsPushReceive(mPushAllowSwitch.isChecked());
            model.setLicense(getLicense());
            model.setDescription(mDescription.getText().toString());
            model.setAddressModel(uploadAddressModel);
            model.setIsExpert(true);
            ServerManager.modifyExpert(new ServerManager.OnServerListener<ExpertModel>() {
                @Override
                protected void onSuccess(ExpertModel data) {
                    ProgressManger.showToast("? ?  ?.");
                    getActivity().onBackPressed();
                }
            }, model);

        }

        private boolean isEmpty(EditText editText) {
            return editText.getText().toString().isEmpty();
        }

        private boolean isProperNumber(String number) {
            return number.matches("(01[016789])(\\d{3,4})(\\d{4})");
        }
    };

    private void setMapView() {
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.googleMap);
        mapFragment.getMapAsync(this);
    }

    private void setLayout() {
        mRegisterView = rootView.findViewById(R.id.modify_content);

        mBackBtn = (ImageButton) mRegisterView.findViewById(R.id.ib_back);
        mBackBtn.setImageResource(R.drawable.ic_dehaze_white_36dp);
        mDuplicateCheckBtn = (Button) rootView.findViewById(R.id.check_duplicate);
        mDuplicateCheckBtn.setVisibility(View.GONE);
        mAuthSendBtn = (Button) rootView.findViewById(R.id.send_code);
        mAuthSendBtn.setVisibility(View.GONE);
        mAuthCheckBtn = (Button) mRegisterView.findViewById(R.id.code_check);
        mAuthCheckBtn.setVisibility(View.GONE);
        mDoneBtn = (Button) mRegisterView.findViewById(R.id.done);
        mDoneBtn.setText("");
        mNameEdit = (EditText) mRegisterView.findViewById(R.id.name);
        mIdEdit = (EditText) mRegisterView.findViewById(R.id.id);
        mIdEdit.setBackgroundColor(Color.parseColor("#00000000"));
        mIdEdit.setTextColor(getResources().getColor(android.R.color.white));
        mIdEdit.setEnabled(false);

        rootView.findViewById(R.id.guide4).setVisibility(View.GONE);
        rootView.findViewById(R.id.code_layout).setVisibility(View.GONE);

        mPhoneEdit = (EditText) mRegisterView.findViewById(R.id.phone);
        mCodeEdit = (EditText) mRegisterView.findViewById(R.id.code);
        mCodeEdit.setVisibility(View.GONE);
        mPasswordEdit = (EditText) mRegisterView.findViewById(R.id.password);
        mPasswordConfirmEdit = (EditText) mRegisterView.findViewById(R.id.password_check);
        mPushAllowSwitch = (Switch) mRegisterView.findViewById(R.id.push_switch);
        mDescription = (EditText) mRegisterView.findViewById(R.id.company_information);

        ((TextView) rootView.findViewById(R.id.textViewTitle)).setText("? ");
        ((RadioButton) rootView.findViewById(R.id.radioButtonSelectMap)).setOnCheckedChangeListener(this);
        ((RadioButton) rootView.findViewById(R.id.radioButtonSelectCity)).setOnCheckedChangeListener(this);

        RecyclerView mRecyclerViewReviews = (RecyclerView) rootView.findViewById(R.id.recyclerViewReview);
        mRecyclerViewReviews
                .setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        mReviewListAdapter = new ReviewListAdapter();
        mRecyclerViewReviews.setAdapter(mReviewListAdapter);
        getReviews();
        initData();
    }

    private void getReviews() {
        ServerManager.getMyReviews(new ServerManager.OnServerListener<List<ReviewModel>>(getContext()) {
            @Override
            protected void onSuccess(List<ReviewModel> data) {
                mReviewModels = data;
                mReviewListAdapter.setData(mReviewModels);
            }
        });
    }

    private void initData() {
        ExpertModel mExpertModel = (ExpertModel) ZipsuriApplication.getUserModel();
        uploadAddressModel = mExpertModel.getAddressModel();
        mIdEdit.setText(mExpertModel.getUserId());
        mPushAllowSwitch.setChecked(mExpertModel.getIsPushReceive());
        for (int i = 0; i < PostModel.FLAG_LICENSE.length; i++) {
            if ((mExpertModel.getLicense() & PostModel.FLAG_LICENSE[i]) != 0) {
                ((CheckableButton) rootView.findViewById(licenseButtonIds[i])).setChecked(true);
            } else {
                ((CheckableButton) rootView.findViewById(licenseButtonIds[i])).setChecked(false);
            }
        }

        mDescription.setText(mExpertModel.getDescription());

    }

    @Override
    public void onMapClick(LatLng latLng) {
        mGoogleMap.clear();
        AddressModel mAddressModelTmp = new AddressModel();
        mAddressModelTmp.setLatitude(latLng.latitude);
        mAddressModelTmp.setLongitude(latLng.longitude);
        ServerManager.reverseGeoCoding(new ServerManager.OnServerListener<AddressModel>(getContext()) {
            @Override
            protected void onSuccess(AddressModel data) {
                setDistance(data);
            }
        }, mAddressModelTmp);
    }

    private void setDistance(final AddressModel addressModel) {
        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(getContext(), R.layout.adapter_single_choice_list);
        final int[] distances = { 5, 10, 30, 50 };
        for (int distance : distances) {
            mAdapter.add(distance + "Km");
        }
        new AlertDialog.Builder(getContext()).setTitle("? ?.").setCancelable(false)
                .setSingleChoiceItems(mAdapter, 0, null)
                .setPositiveButton("?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                        addressModel.setDistance(distances[selectedPosition]);
                        setAddressModel(addressModel);
                    }
                }).show();
    }

    private void setAddressModel(AddressModel addressModel) {
        LatLng mLocation = new LatLng(addressModel.getLatitude(), addressModel.getLongitude());
        mGoogleMap.clear();
        this.uploadAddressModel = addressModel;
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(mLocation);
        mGoogleMap.addMarker(markerOptions);
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.center(mLocation);
        circleOptions.radius(addressModel.getDistance() * 1000);
        circleOptions.strokeColor(Color.parseColor("#00000000"));
        circleOptions.fillColor(getResources().getColor(R.color.colorBackgroundVeryDeep));
        mGoogleMap.addCircle(circleOptions);
        if (addressModel.getDistance() >= 50) {
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLocation, 7));

        } else if ((addressModel.getDistance() >= 30)) {
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLocation, 9));
        } else {
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLocation, 10));

        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.mGoogleMap = googleMap;
        this.mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.541, 126.986), 18));
        this.mGoogleMap.setOnMapClickListener(null);
        setAddressModel(uploadAddressModel);
        Log.d("ttttt", uploadAddressModel.toString());
        if (uploadAddressModel.getDistance() == 0) {
            ((RadioButton) rootView.findViewById(R.id.radioButtonSelectCity)).setOnCheckedChangeListener(null);
            ((RadioButton) rootView.findViewById(R.id.radioButtonSelectCity)).setChecked(true);
            ((RadioButton) rootView.findViewById(R.id.radioButtonSelectCity)).setOnCheckedChangeListener(this);
        } else {
            ((RadioButton) rootView.findViewById(R.id.radioButtonSelectMap)).setChecked(true);
            ((RadioButton) rootView.findViewById(R.id.radioButtonSelectMap)).setOnCheckedChangeListener(this);
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        LocationManager mLocationManager = (LocationManager) getContext()
                .getSystemService(Context.LOCATION_SERVICE);
        if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            ProgressManger.showToast("  .");
        } else {
            ProgressManger.showToast("  ...");
        }
        return false;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
            case R.id.radioButtonSelectMap:
                this.mGoogleMap.setOnMapClickListener(this);
                this.mGoogleMap.setOnMyLocationButtonClickListener(this);
                if (ContextCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mGoogleMap.setMyLocationEnabled(true);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                                MY_LOCATION_REQUEST_CODE);
                    }
                }
                break;
            case R.id.radioButtonSelectCity:
                this.mGoogleMap.setOnMapClickListener(null);
                this.mGoogleMap.setOnMyLocationButtonClickListener(null);
                mGoogleMap.setMyLocationEnabled(false);
                startActivityForResult(new Intent(getContext(), RegisterExpertRegionActivity.class),
                        SELECT_CITY_REQUEST_CODE);
                break;
            }
        }
    }

    private long getLicense() {
        long result = 0;
        for (int i = 0; i < licenseButtonIds.length; i++) {
            if (((CheckableButton) rootView.findViewById(licenseButtonIds[i])).isChecked()) {
                result |= PostModel.FLAG_LICENSE[i];
            }
        }
        return result;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        if (requestCode == MY_LOCATION_REQUEST_CODE) {
            if (permissions.length == 1 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(getContext(),
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                ProgressManger.showToast("?  .");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SELECT_CITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                uploadAddressModel = new AddressModel();
                String address = data.getStringExtra(RegisterExpertRegionActivity.INTENT_ADDRESS);
                uploadAddressModel.setRoadAddr(address);
                Log.d("tttt", uploadAddressModel.toString());
            } else {
                ((RadioButton) rootView.findViewById(R.id.radioButtonSelectCity)).setChecked(false);
            }
        }

        Log.d("tttt", uploadAddressModel.toString());

    }

    private class ReviewListAdapter extends RecyclerView.Adapter<ReviewListAdapter.ReviewHolder> {

        private List<ReviewModel> mReviewModels;

        public void setData(List<ReviewModel> mReviewModels) {
            this.mReviewModels = mReviewModels;
            notifyDataSetChanged();
        }

        public List<ReviewModel> getData() {
            return mReviewModels;
        }

        @Override
        public ReviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ReviewHolder(
                    LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_review_list, parent, false));
        }

        @Override
        public void onBindViewHolder(ReviewHolder holder, int position) {
            ReviewModel mReviewModel = mReviewModels.get(position);
            holder.mTextViewUserId.setText("*****");
            holder.mTextViewContent.setText(mReviewModel.getContent());
            holder.mRatingBarScore.setRating((int) mReviewModel.getScore() / 2);
        }

        @Override
        public int getItemCount() {
            if (mReviewModels == null) {
                return 0;
            } else {
                return mReviewModels.size();
            }
        }

        public class ReviewHolder extends RecyclerView.ViewHolder {

            public TextView mTextViewUserId, mTextViewContent;
            public RatingBar mRatingBarScore;

            public ReviewHolder(View itemView) {
                super(itemView);
                this.mTextViewUserId = (TextView) itemView.findViewById(R.id.textViewUserId);
                this.mTextViewContent = (TextView) itemView.findViewById(R.id.textViewContent);
                this.mRatingBarScore = (RatingBar) itemView.findViewById(R.id.ratingBarScore);

                DrawableCompat.setTint(this.mRatingBarScore.getProgressDrawable(), Color.YELLOW);

            }

        }

    }
}