Monday, 13 June 2016

Android signup

package com.tdi.rk;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Signup extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    EditText et_name, et_email, et_ref, et_city, et_pin, et_storenm, et_mobile;
    Button btn_signup;
    ImageView iv_profile;
    String state_id, state_name;
    String name, mail, password, city, state, store_name;
    Spinner sp_state, sp_city, sp_dist;
    AQuery aQuery;
    ProgressDialog pd;
    ByteArrayOutputStream stream;
    Bitmap bitmap;
    String picturepath, encoadedString;
    Map<String, Object> params;
    ArrayList<StateBean> stateBean;
    ArrayList<String> al_statee;
    ArrayList<String> al_city;
    String city_url;
    String my_state, my_dist, my_city;
    private Uri filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        initStuff();
        spinState();
        if (!isNetworkConnected()) {
            Toast.makeText(getApplicationContext(), "please check Your internet connection", Toast.LENGTH_LONG).show();
        } else {


                    onCLickEvent();





        }
    }

    private void spinState() {
        stateBean = new ArrayList<StateBean>();
        al_statee = new ArrayList<String>();
        AQuery aq_state = new AQuery(this);
        String st_url = "http://rajkotkitchenware.com/rkapp/State.php?key=5a14ec5b310164f2dfe49e86b06124a";
        aq_state.ajax(st_url, JSONObject.class, new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject object, AjaxStatus status) {


                JSONObject jsonObject;
                JSONArray jsonArray = object.optJSONArray("state");
                Log.d("JsonArray", jsonArray.toString());
                StateBean sb = new StateBean();
                if (object.opt("data").equals("success")) {
                    //jsonArray.optString()
                    for (int i = 0; i < jsonArray.length(); i++) {
                        try {
                            jsonObject = jsonArray.getJSONObject(i);
                            state_id = jsonObject.optString("stateID");
                            Log.d("state ID", state_id);
                            sb.setState_id(state_id);
                            state_name = jsonObject.optString("Name");


                            stateBean.add(sb);

                            al_statee.add(state_name);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        sp_state.setAdapter(new ArrayAdapter<String>(Signup.this, android.R.layout.simple_spinner_dropdown_item, al_statee));

                    }


                }

            }

        });

    }


    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

    public void initStuff() {
        et_ref = (EditText) findViewById(R.id.et_ref);
        et_name = (EditText) findViewById(R.id.et_name);
        et_email = (EditText) findViewById(R.id.et_email);
        // et_pass = (EditText) findViewById(R.id.et_pass);
        et_city = (EditText) findViewById(R.id.et_city);
        et_pin = (EditText) findViewById(R.id.et_pincode);

        et_storenm = (EditText) findViewById(R.id.et_store_nm);
        et_mobile = (EditText) findViewById(R.id.et_mobno);

        sp_state = (Spinner) findViewById(R.id.sp_state);
        //  sp_city = (Spinner) findViewById(R.id.sp_city);
        sp_dist = (Spinner) findViewById(R.id.sp_district);
        sp_state.setOnItemSelectedListener(this);


        iv_profile = (ImageView) findViewById(R.id.profile_image);
        btn_signup = (Button) findViewById(R.id.btn_signup);

        aQuery = new AQuery(this);
        pd = new ProgressDialog(this);
        pd.setMessage("loading...");


        try {
            iv_profile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final String items[] = {"Camera", "Gallery", "Cancle"};

                    AlertDialog.Builder pickimage = new AlertDialog.Builder(Signup.this);
                    pickimage.setTitle("pick image");
                    pickimage.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            if (items[which].equals("Camera")) {

                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent, 0);

                            } else if (items[which].equals("Gallery")) {

                                Intent i = new Intent(
                                        Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                i.setType("image/*");
                                startActivityForResult(Intent.createChooser(i, "Select Image"), 1);

                            } else if (items[which].equals("Cancle")) {
                                dialog.dismiss();
                            }

                        }
                    });
                    pickimage.show();

                   /* Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    i.setType("image*//*");
                    startActivityForResult(i, 1);*/
                    //
                }
            });
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");
                Log.d("Destination", destination.toString());
                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                iv_profile.setImageBitmap(thumbnail);
                encoadedString = bitmapToBase64(thumbnail);

            } else if (requestCode == 1) {
                Uri selectImage = data.getData();
                String[] filePathColunm = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectImage, filePathColunm, null, null, null);
                cursor.moveToFirst();

                int colunmIndex = cursor.getColumnIndex(filePathColunm[0]);
                picturepath = cursor.getString(colunmIndex);
                cursor.close();

                iv_profile.setImageBitmap(BitmapFactory.decodeFile(picturepath));
                encoadedString = bitmapToBase64(BitmapFactory.decodeFile(picturepath));
               // Log.d("IMage", "Encoaded" + encoadedString);


            }
        }
    }

    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    private void onCLickEvent() {


        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isNetworkConnected()) {

                    if (checkValidation()) {
                        isRegister();
                    } else {
                        Toast.makeText(getApplicationContext(), "Please enter all field", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_LONG).show();
                }
            }
        });
    }


    public boolean emailValidator(String email) {
        Pattern pattern;
        Matcher matcher;
        final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(email);
        return matcher.matches();
    }

    private boolean checkValidation() {
        boolean check = true;

        if (et_email.getText().toString().trim().equals("")) {
            et_email.setError("please enter valid  e-mail address");
            check = false;
            return check;

        }
        else if(!emailValidator(et_email.getText().toString().trim())){
                et_email.setError("enter valid email address");
            check=false;
            return check;
        }

         else if (et_pin.getText().toString().length()<6) {
            et_pin.setError("please enter pincode");
            check = false;
            return check;
        }
         else if (et_mobile.getText().toString().trim().length() < 10) {
            et_mobile.setError("enter mobile number");
            check = false;
            return check;
        } else {

        }
        return check;
    }

    private void isRegister() {
        String url = "http://www.rajkotkitchenware.com/rkapp/Registration.php";
        // String url ="http://www.programmingly.com/bvn/rk/Registration.php";
        params = new HashMap<String, Object>();
        if (et_name.getText().toString().equals("")) {
            params.put("name", null);
        } else {
            params.put("name", et_name.getText().toString());
        }
        if(!emailValidator(et_email.getText().toString())){
            et_email.setError("please enter valid email Address");
        }else {
            params.put("email", et_email.getText().toString());
        }

        params.put("mobile", et_mobile.getText().toString());
        if (bitmap == null) {
            params.put("image", encoadedString);
        } else {
            params.put("image", encoadedString);
        }
        if (et_storenm.getText().toString().equals("")) {
            params.put("company", null);
        } else {
            params.put("company", et_storenm.getText().toString());
        }
        // params.put("city", my_city);
        params.put("district", my_dist);
        params.put("pin",et_pin.getText().toString().trim());
        params.put("state", my_state);

        if (et_city.getText().toString().equals("")) {
            params.put("city", null);
        } else {
            params.put("city", et_city.getText().toString());
        }
        /*if (et_state.getText().toString().equals("")) {
            params.put("state", null);
        } else {
            params.put("state", et_state.getText().toString());
        }*/
        if (et_ref.getText().toString().equals("")) {
            params.put("referenceBy", null);
        } else {
            params.put("referenceBy", et_ref.getText().toString());
        }
        params.put("key", "5a14ec5b310164f2dfe49e86b06124a");

        aQuery.progress(pd).ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject object, AjaxStatus status) {
                if (object != null) {
                    String msg = object.optString("msg");

                    //successful
                    if (object.optString("data").equals("success")) {
                        startActivity(new Intent(Signup.this, Login.class));
                        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


        my_state = sp_state.getSelectedItem().toString();

        //Toast.makeText(getApplicationContext(),sta,Toast.LENGTH_LONG).show();
        //String s = String.valueOf(state_id.length()-1);

        city_url = "http://rajkotkitchenware.com/rkapp/District.php?stateID=" + my_state + "&key=5a14ec5b310164f2dfe49e86b06124a";
        //city_url = "http://rajkotkitchenware.com/rkapp/City.php?stateID="+sta+"&key=5a14ec5b310164f2dfe49e86b06124a";
//        Log.d("stateid recev ",sb.getState_id().toString());
        //  Log.d("al",al.toString());
        Log.d("city url", city_url);
        AQuery aq_city = new AQuery(this);
        ProgressDialog pd = new ProgressDialog(this);
        al_city = new ArrayList<String>();

        aq_city.progress(pd).ajax(city_url, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject object, AjaxStatus status) {
                JSONArray jsonArray_city = object.optJSONArray("state");
                JSONObject jsonObject_city;
                for (int i = 0; i < jsonArray_city.length(); i++) {

                    try {
                        jsonObject_city = jsonArray_city.getJSONObject(i);

                        String city_id = jsonObject_city.optString("cityID");
                        String city_name = jsonObject_city.optString("Name");

                        al_city.add(city_name);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    sp_dist.setAdapter(new ArrayAdapter<String>(Signup.this, android.R.layout.simple_spinner_dropdown_item, al_city));
                    final JSONObject finalJsonObject_city = null;
                    sp_dist.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            my_dist = sp_dist.getSelectedItem().toString();
                            String mycity_url = "http://rajkotkitchenware.com/rkapp/City.php?stateID=" + my_dist + "&key=5a14ec5b310164f2dfe49e86b06124a";

                            AQuery aq_mycity = new AQuery(Signup.this);
                            aq_mycity.ajax(mycity_url, JSONObject.class, new AjaxCallback<JSONObject>() {

                                @Override
                                public void callback(String url, JSONObject object, AjaxStatus status) {

                                    JSONArray jsonArray_mycity = object.optJSONArray("state");
                                    JSONObject jsonObject_mycityy = null;
                                    for (int i = 0; i < jsonArray_mycity.length(); i++) {

                                        try {
                                            jsonObject_mycityy = jsonArray_mycity.getJSONObject(i);
                                            String city_id = jsonObject_mycityy.optString("cityID");
                                            String city_name = finalJsonObject_city.optString("Name");
                                            al_city.add(city_name);
                                            sp_city.setAdapter(new ArrayAdapter<String>(Signup.this, android.R.layout.simple_spinner_dropdown_item, al_city));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                            });


                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {


                        }
                    });
                }
            }
        });


    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

No comments:

Post a Comment