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!!!!!!