Thursday, 30 March 2017

Android cropping image from camera or gallery.

Creating New Project.

Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project. 
 compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.jakewharton:butterknife:8.4.0'



Create Xml file in project.    
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/preImage"
        android:layout_width="144dp"
        android:layout_height="144dp"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:src="@mipmap/ic_launcher"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"></de.hdodenhof.circleimageview.CircleImageView>

</RelativeLayout>



Create the Java file in project.

Open app => main => src = MainActivity.java

import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.soundcloud.android.crop.Crop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import de.hdodenhof.circleimageview.CircleImageView;
import static journal.shibboleth.com.croperactivity.MarshMallowPermission.CAMERA_PERMISSION_REQUEST_CODE;
import static journal.shibboleth.com.croperactivity.MarshMallowPermission.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE;

public class MainActivity extends AppCompatActivity {

    private static final int CAMERA_REQUEST = 108;
    private String mCurrentPhotoPath = "";

    private MarshMallowPermission marshMallowPermission;
    private int mAddedItems = 0;
    private ProgressDialog mProgressDialog;

    private boolean isUpdated = false;

    CircleImageView mPreImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPreImageView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.preImage);

        mPreImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CheckVersions.isMarshmallow()) {
                    marshMallowPermission =
                            new MarshMallowPermission(MainActivity.this);
                    if (!marshMallowPermission.checkPermissionForCamera()) {
                        marshMallowPermission.requestPermissionForCamera();
                    } else {
                        if (!marshMallowPermission.checkPermissionForExternalStorage()) {
                            marshMallowPermission.requestPermissionForExternalStorage();
                        } else {
                            clickImage();
                        }
                    }
                } else {
                    clickImage();
                }
            }
        });


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home) {
            Intent returnIntent = new Intent();
            setResult(RESULT_CANCELED, returnIntent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_PERMISSION_REQUEST_CODE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (!marshMallowPermission.checkPermissionForExternalStorage()) {
                        marshMallowPermission.requestPermissionForExternalStorage();
                    } else {
                        clickImage();
                    }
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "Camera permission needed." +
                            " Please allow in App Settings for additional " +
                            "functionality.", Toast.LENGTH_LONG).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            case EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    clickImage();
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "External Storage permission needed. " +
                            "Please allow in App Settings for additional" +
                            " functionality.", Toast.LENGTH_LONG).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }

            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }


    private void clickImage() {
        final CharSequence[] items = {"Take Photo Camera", "Take Photo Gallery"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo Camera")) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
                        // Create the File where the photo should go
                        File photoFile;
                        photoFile = createImageFile();
                        // Continue only if the File was successfully created
                        if (photoFile != null) {
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        } else {
                            mCurrentPhotoPath = "";
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        }

                    }
                } else if (items[item].equals("Take Photo Gallery")) {
                    Crop.pickImage(MainActivity.this);
                }
            }
        });
        builder.show();
    }

    private File createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  // prefix
                    ".jpg",         // suffix
                    storageDir      // directory

            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Save a file: path for use with ACTION_VIEW intents
        if (image != null) {
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            Log.i("Ihdh", "Image" + mCurrentPhotoPath);
        }
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode != RESULT_CANCELED) {
            if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
                beginCrop(result.getData());
            } else if (requestCode == Crop.REQUEST_CROP) {
                handleCrop(resultCode, result);
            } else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
                if (mCurrentPhotoPath == null || mCurrentPhotoPath.isEmpty()) {
                    beginCrop(result.getData());
                } else {
                    beginCrop(Uri.parse(mCurrentPhotoPath));
                }
            }
        }
    }

    private void beginCrop(Uri source) {
        try {
            File file = MainActivity.this.getCacheDir();
            deleteDir(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        Crop.of(source, destination).asSquare().start(this, Crop.REQUEST_CROP);
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir != null && dir.delete();
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            try {
                mPreImageView.setImageDrawable(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Log.i("CROP", "handleCrop: " + Crop.getOutput(result));
                mPreImageView.setImageURI(Crop.getOutput(result));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            try {
                Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String saveToInternalStorage(Bitmap bitmapImage) {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        String name = System.currentTimeMillis() + "_image.jpg";
        File mypath = new File(directory, name);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 50, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return directory.getAbsolutePath() + "/" + name;
    }

}

Android Working with Marshmallow (M) Runtime Permissions.

Create the Java file in project.
Open app => main => src = CheckVersions.java


import android.os.Build;

/**
 * Created by Laptop on 24-10-2016.
 */

public class CheckVersions {
    public static boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
}



Create the Java file in project.
Open app => main => src = MarshMallowPermission.java

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

/**
 * Created by pc on 10/26/2016.
 */

public class MarshMallowPermission {
    public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
    public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;
    Activity activity;

    public MarshMallowPermission(Activity activity) {
        this.activity = activity;
    }


    public boolean checkPermissionForExternalStorage() {
        int result = ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    public boolean checkPermissionForCamera() {
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
        return result == PackageManager.PERMISSION_GRANTED;
    }


    public void requestPermissionForExternalStorage() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(activity, "External Storage permission needed. " +
                    "Please allow in App Settings for additional" +
                    " functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        }
    }

    public void requestPermissionForCamera() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.CAMERA)) {
            Toast.makeText(activity, "Camera permission needed." +
                    " Please allow in App Settings for additional " +
                    "functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.CAMERA},
                    CAMERA_PERMISSION_REQUEST_CODE);
        }
    }

}


Add Internet permission in your manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Thursday, 1 September 2016

How to share the GPS location on Whatspp in Android Studio.

Creating New Project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.   
Open => app => res => layout - activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/image"
    android:paddingBottom="64dp"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="64dp">

    <Button
        android:id="@+id/btnShowLocation"
        android:layout_width="match_parent"
        android:layout_height="36dp"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:background="@drawable/btn_back"
        android:text="SEND LOCATION"
        android:textColor="@color/colorPrimary" />

</RelativeLayout>


Create the Java file in project.
Open app => main => src = GPSTracker.java.

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}


Create the Java file in project.
Open app => main => src = GPSLocationActivity.java.

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GPSLocationActivity extends Activity {

    Button btnShowLocation;
    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // create class object
                gps = new GPSTracker(GPSLocationActivity.this);

                // check if GPS enabled       
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder geocoder = new Geocoder(GPSLocationActivity.this, Locale.ENGLISH);

                    try {
                        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);

                        if (addresses != null) {
                            Address returnedAddress = addresses.get(0);
                            StringBuilder strReturnedAddress = new StringBuilder();
                            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                            }
                            final String address = strReturnedAddress.toString();
                            String message = "Latitude: " + latitude + "\n" + "Longitude: " + longitude;

                            Intent sendIntent = new Intent();
                            sendIntent.setAction(Intent.ACTION_SEND);
                            sendIntent.putExtra(Intent.EXTRA_TEXT, address);
                            sendIntent.setType("text/plain");
                            // Do not forget to add this to open whatsApp App specifically
                            sendIntent.setPackage("com.whatsapp");
                            startActivity(sendIntent);
                            finish();
                        } else {
                            Toast.makeText(GPSLocationActivity.this, "No Address returned!", Toast.LENGTH_LONG).show();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Toast.makeText(GPSLocationActivity.this, "Canont get Address!", Toast.LENGTH_LONG).show();
                    }
                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }

            }
        });
    }
}

Add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />



 May this code help you. Thanks!!!!!!
 

Friday, 12 August 2016

Automatically Read income message to verify OTP, automatically fill in edit field and Redirect Android Studio.

Creating New Project.
Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.    
Open => app => res => layout - activity_otp.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#33cc88">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtMobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Please Enter your OTP below:"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="@color/colorText"
                android:textSize="18dp" />

            <EditText
                android:id="@+id/etOtp"
                android:layout_width="146dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:ems="10"
                android:inputType="number"
                android:background="#ffffff"
                android:paddingLeft="4dp" />

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

   

Create the Java file in project.
Open app => main => src = OtpActivity.java.

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class OtpActivity extends AppCompatActivity {
    public static EditText otpEditText;
    ProgressDialog dialog;
    public static final String KEY_OTP = "";
    String URL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otp);
        //Getting the Widget Id
        Init();
      
        //Automatically reditrect the screen

         otpEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Handler h = new Handler(Looper.getMainLooper());
                h.postDelayed(new Runnable() {
                    public void run() {
                        if (otpEditText.length() > 0) {
                            otpRegister();
                        }
                    }
                }, 6000);
            }
        });
    }

    private void Init() {
        otpEditText = (EditText) findViewById(R.id.etOtp);
    }

    private void otpRegister() {
        final String mOtp = otpEditText.getText().toString();
        //SHOWING THE DIALOG
        showDialog(true);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        Toast.makeText(OtpActivity.this, response, Toast.LENGTH_LONG).show();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
                        Toast.makeText(OtpActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(
KEY_OTP, "");
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(OtpActivity.this, "", "Sending.....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

   private void OpenScreen() {
        Intent i = new Intent(OtpActivity.this, ChooseActivtiy.class);
        startActivity(i);
    }
   //Here is fill the OTP verify code.
    public void setOtp(String otp) {

        try {
           //****Only fill here 4 digit number***//
            Pattern p = Pattern.compile("(\\d{4})");//. represents single character
            Matcher m = p.matcher(otp);
            if (m.find()) {
                String b = m.group(1);
                otpEditText.setText(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Create the Java file in project.

Open app => main => src = SmsReceiver .java.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import com.sell.vevsa.OtpActivity;


public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    try {
                        if (senderNum.equals("HP-VERIFY")) {
                            OtpActivity Sms = new OtpActivity();
                            Sms.setOtp(message);
                        }
                    } catch (Exception e) {
                    }
                }
            }

        } catch (Exception e) {

        }
    }
}


Add permission and receiver in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<receiver android:name=".SmsReceiver ">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

May this code help you. Thanks!!!!!!

Thursday, 11 August 2016

Create Dynamic views in Andorid Studio.

Creating New Project.
Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.   
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="desktop.laptop.com.customdemo.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/linearPlus"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerInParent="true"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_marginTop="16dp"
                android:gravity="center"
                android:orientation="vertical">

                <Button
                    android:id="@+id/btPlus"
                    android:layout_width="32dp"
                    android:layout_height="36dp"
                    android:text="+"
                    android:textColor="#000000" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</android.support.constraint.ConstraintLayout>


Create Add View file in project.   

Open => app => res => layout - add_view.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp"
    android:background="#cccccc"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="18dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtBook"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Guide(s)"
            android:textColor="#000000" />

        <EditText
            android:id="@+id/etBook"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="68dp"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:paddingLeft="8dp"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="18dp"
        android:layout_marginTop="12dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtAuthor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Author/Publisher"
            android:textColor="#000000" />

        <EditText
            android:id="@+id/etAuthor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:paddingLeft="8dp"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>


Create the Java file in project.
Open app => main => src = MainActivity.java.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    List<ModelBook> dataArray = new ArrayList<>();
    List<ModelBookUI> UIArray = new ArrayList<>();
    int position = 0;
    Button plusButton;
    LinearLayout plusLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        plusLinearLayout = (LinearLayout) findViewById(R.id.linearPlus);
        plusButton = (Button) findViewById(R.id.btPlus);

        plusButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                position = UIArray.size();

                UIArray.add(AddView("lay" + position, position, plusLinearLayout));
            }
        });

    }

    /**********************
     * Add new view
     **************************/
    private ModelBookUI AddView(String tag, int position, LinearLayout parent) {

        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);

        View child = inflater.inflate(R.layout.add_book, parent, false);

        EditText book = (EditText) child.findViewById(R.id.etBook);
        EditText author = (EditText) child.findViewById(R.id.etAuthor);

        LinearLayout root = (LinearLayout) child.findViewById(R.id.root);

        root.setTag(tag);

        ModelBookUI model = new ModelBookUI();

        model.book_name = book;
        model.author = author;

        parent.addView(child);

        return model;
    }
}

Create the Java file in project.
Open app => main => src = ModelBook.java.

public class ModelBook {

    public String book;
    public String author;
}


Create the Java file in project.
Open app => main => src = ModelBookUI.java.

import android.widget.EditText;

public class ModelBookUI {

    public EditText book_name;
    public EditText author;
}





Screen Shot:-


Button Click
Add View

May this code help you. Thanks!!!!!!

Tuesday, 9 August 2016

Retrofit Android studio post the data on Server.

We will post the following data.
{
"token":"6536a951423727727c47ed18004e2f30z",
"book_req_category": 1,
"books": [{
    "name": "Flamingo",
    "Class": "12th",
    "medium": "English",
    "is_ncert": 1,
    "publisher_name": "NCERT",
    "type": 0
}]
}


Creating New Project.

Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Volley Library to our project.  
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'


Create the Api Client java class in project.
Open app => main => src = ApiClient.java

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Laptop on 8/9/2016.
 */
public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl("http://books.vevsa.com:7001/")
                    .client(new OkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}


Create the Response java class in project.
Open app => main => src = Response.java

import com.google.gson.annotations.SerializedName;

/**
 * Created by Laptop on 8/9/2016.
 */
public class Response {
    @SerializedName("log")
    private String log;

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    @SerializedName("flag")
    private int flag;
}


Create the Interface in project.
Open app => main => src = RetrofitInterface

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
/**
 * Created by Laptop on 8/9/2016.
 */

public interface RetrofitInterface {
    //TODO: Please check curly bracket at end point of api name :)
    @POST("req_book_auth/raise_request")
    @Headers("Accept: application/json")
    Call<Response> getAllData(@Body RequestBody params);
}


Create the Java file in project.
Open app => main => src = MainActivity.java

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;


public class MainActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getData();
    }

    private void getData() {
        showDialog();
        JSONObject jsonObject = getObject();
        RequestBody body = null;
        if ((jsonObject) != null) {
            Log.i("JSON_DATA", "Json" + jsonObject);
            body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                    (jsonObject).toString());
            RetrofitInterface retrofitInterface = ApiClient.getClient().create(RetrofitInterface.class);
            Call<Response> call = retrofitInterface.getAllData(body);
            call.enqueue(new Callback<Response>() {
                @Override
                public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                    closeDialog();
                    Log.i("RESPONSE", "code" + response.code());

                    try {
                        Log.i("RESPONSE", "Flag:::" + response.body().getFlag());
                        Log.i("RESPONSE", "Log:::" + response.body().getLog());
                        if (response.code() == HttpURLConnection.HTTP_OK) {
                            if (response.body().getFlag() == 143) {
                                //     Toast.makeText(getApplicationContext(),"dlkashdsh"+response.body().getLog(),Toast.LENGTH_LONG).show();
                                Log.i("RESPONSE", "Success");
                            } else {
                                Log.i("RESPONSE", "Failure");
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(Call<Response> call, Throwable t) {
                    Log.i("RESPONSE", "Error" + t.getMessage());
                    closeDialog();
                }
            });
        } else {
            Log.i("RESPONSE", "Error");
            closeDialog();
        }

    }

    private void showDialog() {
        progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading...");
    }

    private void closeDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private JSONObject getObject() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", "6536a951423727727c47ed18004e2f30");
            jsonObject.put("book_req_category", 1);
            JSONArray jsonArray = new JSONArray();
            JSONObject object = new JSONObject();
            object.put("name", "Flamingo");
            object.put("Class", "12th");
            object.put("medium", "English");
            object.put("is_ncert", 1);
            object.put("publisher_name", "NCERT");
            object.put("type", 0);
            jsonArray.put(object);
            jsonObject.put("books", jsonArray);
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }
}



Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!