Thursday, 8 June 2017

Currency Convertor



STEP -1 : CurrencyConvertor.php, Save in WAMPP/XAMPP localhost root folder

CurrencyConvertor.php - Convert one currency to other

<?php
function currencyConvertor($amount,$from_Currency,$to_Currency) {
     $amount = urlencode($amount);
      $from_Currency = urlencode($from_Currency);
      $to_Currency = urlencode($to_Currency);
      $get = "https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";
      $ch = curl_init();
                                        $url = $get;
                                        // Disable SSL verification
                                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                                        // Will return the response, if false it print the response
                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                        // Set the url
                                        curl_setopt($ch, CURLOPT_URL,$url);
                                        // Execute
                                        $result=curl_exec($ch);
                                        // Closing
                                        curl_close($ch);
      $get = explode("<span class=bld>",$result);
      $get = explode("</span>",$get[1]); 
      $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
      //return number_format($converted_amount, 2, '.', '');
 return round($converted_amount, 3);
   
}

if(isset($_POST['amount']) && isset($_POST['fromc']) && isset($_POST['to']))
 {

         $amount = $_POST['amount'];
         $fromc = $_POST['fromc'];
        $to   = $_POST['to'];
        $curr =   currencyConvertor($amount,$fromc,$to);
        echo json_encode($curr);
 }

?>
--------------------------------------------------------------------------

STEP-2 : CurrencyCode.php - Save in root folder. It fetch all country with their currency code in a JSON format.

CurrencyCode.php
---------------------- ---------------------------------------------------------

<?php
function currencyConvertor($amount,$from_Currency,$to_Currency) {
     $amount = urlencode($amount);
      $from_Currency = urlencode($from_Currency);
      $to_Currency = urlencode($to_Currency);
      $get = "https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";
      $ch = curl_init();
                                        $url = $get;
                                        // Disable SSL verification
                                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                                        // Will return the response, if false it print the response
                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                        // Set the url
                                        curl_setopt($ch, CURLOPT_URL,$url);
                                        // Execute
                                        $result=curl_exec($ch);
                                        // Closing
                                        curl_close($ch);
      $get = explode("<span class=bld>",$result);
      $get = explode("</span>",$get[1]); 
      $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
      //return number_format($converted_amount, 2, '.', '');
 return round($converted_amount, 3);
   
}

if(isset($_POST['amount']) && isset($_POST['fromc']) && isset($_POST['to']))
 {

         $amount = $_POST['amount'];
         $fromc = $_POST['fromc'];
        $to   = $_POST['to'];
        $curr =   currencyConvertor($amount,$fromc,$to);
        echo json_encode( $curr);
       
    /*    $json[] = array("amount"=>$curr);
        echo json_encode(array('record'=>$json));*/
       
 }

?>

----------------------------------------------------------------

NOW, WE START ANDROID CODE

STEP-3 : Add below library to App level Gradle

-----------------------------------------------------------------------------
compile 'com.squareup.okhttp3:okhttp:3.8.0'compile 'com.squareup.okhttp3:okhttp:3.8.0'compile 'com.squareup.picasso:picasso:2.5.2'
-----------------------------------------------------------------------------

STEP - 4 : activity_main.xml
---------------------------------------------
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    android:padding="16dp"    android:gravity="center_horizontal|center_vertical"    tools:context="cmsecomm.ecommerce.app.com.currencyconvertor.MainActivity">
    // FIRST

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:weightSum="2">
        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:orientation="vertical">
            <LinearLayout                android:id="@+id/ll1"                android:layout_width="120dp"                android:layout_height="68dp"                android:layout_gravity="center_horizontal"                android:background="#eeeeee"                android:orientation="vertical"                android:paddingLeft="16dp">
                <TextView                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:text="Currency"                    android:textColor="#000000"                    android:textSize="20dp" />
                <Spinner                    android:id="@+id/idSpnFromCountry"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:dropDownWidth="148dp" />            </LinearLayout>        </LinearLayout>
        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:orientation="vertical">
            <LinearLayout                android:id="@+id/ll2"                android:layout_width="120dp"                android:layout_height="68dp"                android:layout_gravity="center_horizontal"                android:background="#eeeeee"                android:orientation="vertical"                android:paddingLeft="16dp">
                <TextView                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:text="Amount"                    android:textColor="#000000"                    android:textSize="20dp" />
                <EditText                    android:id="@+id/et"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:digits=".0123456789"                    android:hint="Enter No."                    android:textColor="#000000"                    android:textColorHint="#aaaaaa" />            </LinearLayout>        </LinearLayout>
    </LinearLayout>
    // -------------REFRESH BUTTON
    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical"        android:layout_marginTop="24dp"        android:layout_marginBottom="24dp"        >        <ImageView            android:id="@+id/idBtnCur"            android:layout_width="64dp"            android:layout_height="64dp"            android:src="@drawable/ic_refresh_512"            android:layout_gravity="center_vertical|center_horizontal"            />    </LinearLayout>    //
    // SECOND ------------------------------

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:weightSum="2">
        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:orientation="vertical">
            <LinearLayout                android:id="@+id/ll3"                android:layout_width="120dp"                android:layout_height="68dp"                android:layout_gravity="center_horizontal"                android:background="#eeeeee"                android:paddingLeft="16dp"                android:paddingRight="16dp"                android:orientation="vertical">
                <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="Currency"                android:textColor="#000000"                    android:textSize="20dp"                />
                <Spinner                    android:id="@+id/idSpnToCountry"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:dropDownWidth="148dp" />            </LinearLayout>        </LinearLayout>

        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:orientation="vertical">        <LinearLayout            android:id="@+id/ll4"            android:layout_width="120dp"            android:layout_height="68dp"            android:layout_gravity="center_horizontal"            android:background="#eeeeee"            android:paddingLeft="16dp"            android:paddingRight="16dp"            android:orientation="vertical">
            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="Amount"                android:textColor="#000000"                android:textSize="20dp"                />
            <TextView                android:id="@+id/tv"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:hint="Result"                android:textSize="20dp"                 />        </LinearLayout>    </LinearLayout>
</LinearLayout>
    // SINGLE DATA
    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:weightSum="2"        android:layout_marginTop="16dp"        >        <TextView            android:id="@+id/idSingleValTV"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:text="Single Val"            android:textColor="#000000"            android:layout_weight="1"            android:gravity="center_horizontal"            />        <TextView            android:id="@+id/idSingleResultTV"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:text="Result Val"            android:textColor="#000000"            android:layout_weight="1"            android:gravity="center_horizontal"            />    </LinearLayout>
    <TextView        android:id="@+id/idDesc"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="16dp"        />        <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:weightSum="2"        android:layout_marginTop="16dp"        >        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:orientation="vertical"            android:layout_weight="1"            android:gravity="center_horizontal"            >
            <ImageView                android:layout_width="64dp"                android:layout_height="64dp"                android:src="@drawable/ic_help" />            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="HELP"                android:textAllCaps="true"                android:layout_marginTop="8dp"                />        </LinearLayout>         <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:orientation="vertical"             android:layout_weight="1"             android:gravity="center_horizontal"            >
             <ImageView                 android:layout_width="64dp"                 android:layout_height="64dp"                 android:src="@drawable/ic_mail" />             <TextView                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:text="MAIL"                 android:textAllCaps="true"                 android:layout_marginTop="8dp"                 />        </LinearLayout>
    </LinearLayout>
    </LinearLayout>
----------------------------------------------------

STEP-5 : MainActivity.java
---------------------------------------------------------------------------------------------
import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.Spinner;import android.widget.TextView;import java.text.NumberFormat;import java.text.ParseException;import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();    EditText et;    Spinner spnFromC, spnToC;    TextView tv, tvSingleVal, tvSingleResult, tvDesc;    ImageView btnCur;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        // VIEW INITIALIZE        et = (EditText)findViewById(R.id.et) ;        spnFromC = (Spinner)findViewById(R.id.idSpnFromCountry);        spnToC = (Spinner)findViewById(R.id.idSpnToCountry);        tv = (TextView)findViewById(R.id.tv);        btnCur = (ImageView) findViewById(R.id.idBtnCur);        tvSingleVal = (TextView)findViewById(R.id.idSingleValTV);        tvSingleResult = (TextView)findViewById(R.id.idSingleResultTV);        tvDesc = (TextView)findViewById(R.id.idDesc);        tvDesc.setText(R.string.description);

        getCountryCurData();        btnCur.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                String amount = et.getText().toString();
                String fromc = spnFromC.getItemAtPosition(spnFromC.getSelectedItemPosition()).toString();                String toc = spnToC.getItemAtPosition(spnToC.getSelectedItemPosition()).toString();                String[] curData = {amount, fromc, toc};                getConvertedValue(curData);
                // TEXTVIEW DATA                tvSingleVal.setText("1.00 "+spnFromC.getSelectedItem().toString());                try {
                    Thread.sleep(2000);                } catch (InterruptedException e) {
                    e.printStackTrace();                }
                tvSingleResult.setText(getSingleValue()+" "+spnToC.getSelectedItem());
            }
        });    }

    public void getConvertedValue(String[] curData)
    {
        new JsonConvertAdapter(MainActivity.this){
            @Override            protected void onPostExecute(String s) {
                super.onPostExecute(s);                if(!s.equals(""))
                {
                    tv.setText(s);                }
            }
        }.execute(curData);    }

    public void getCountryCurData()
    {
        new JsonAdapter(MainActivity.this)
        {
            @Override            protected void onPostExecute(ArrayList<JsonPOJO> stringHashMap) {
                super.onPostExecute(stringHashMap);                if(stringHashMap != null)
                {
                    CustomSpinnerAdapter customAdapter = new CustomSpinnerAdapter(MainActivity.this, stringHashMap);                    spnFromC.setAdapter(customAdapter);                    spnToC.setAdapter(customAdapter);                }
            }
        }.execute();    }

    public int getSingleValue()
    {
        int total_cal=0;        try {
        String s1 = et.getText().toString().trim();        String s2 = tv.getText().toString().trim();
            int count = NumberFormat.getInstance().parse(s1).intValue();            int value = NumberFormat.getInstance().parse(s2).intValue();           total_cal = value/count;
        }catch (NullPointerException npe)
        {
            Log.e(TAG, "Err: "+npe, npe);        } catch (ParseException e) {
            e.printStackTrace();        }
        return total_cal;    }
}
----------------------------------------------------------------------------------------------

STEP-6 : custom_spinner_items.xml

--------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal" android:layout_width="match_parent"    android:layout_height="42dp"    android:weightSum="2"    >    <ImageView        android:id="@+id/iv"        android:layout_width="48dp"        android:layout_height="match_parent"        android:src="@drawable/ic_img_avail"        android:visibility="gone"        />    <TextView        android:id="@+id/idTV1"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="text1"        android:layout_weight="1"        android:visibility="gone"        />
    <TextView        android:id="@+id/idTV2"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1"        android:text="text1"        android:textSize="20dp"        android:textStyle="bold"        android:layout_marginLeft="8dp"        android:gravity="center_vertical|center_horizontal"        />
</LinearLayout>
------------------------------------------------------------------------------------------

STEP-7 : CustomSpinnerAdapter

-----------------------------------------------------------------------------------
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;import com.squareup.picasso.Picasso;import java.util.ArrayList;
/** * Created by Divakar on 6/5/2017. */
public class CustomSpinnerAdapter extends BaseAdapter {

    Context mContext;    ArrayList<JsonPOJO> hmJson = new ArrayList<>();;    LayoutInflater inflater;    TextView tv1, tv2;    ImageView iv1;
    CustomSpinnerAdapter(Context context, ArrayList<JsonPOJO> hmJson)
    {
        mContext = context;        this.hmJson = hmJson;        inflater= (LayoutInflater.from(context));    }
    @Override    public int getCount() {
        return hmJson.size();    }

    @Override    public Object getItem(int position) {
        return hmJson.get(position).getCcur();    }

    @Override    public long getItemId(int position) {
        return 0;    }

    @Override    public View getView(int position, View convertView, ViewGroup parent) {
        View itemView = inflater.inflate(R.layout.custom_spinner_items, parent, false);
        iv1 = (ImageView)itemView.findViewById(R.id.iv) ;        tv1 = (TextView)itemView.findViewById(R.id.idTV1);        tv2 = (TextView)itemView.findViewById(R.id.idTV2);        String ccode = hmJson.get(position).getCountry_code().toLowerCase();        Picasso.with(mContext)
                .load("http://caches.space/flags/"+ccode+".png")
                .fit()
                .centerCrop()
                .into(iv1);
        tv1.setText(hmJson.get(position).getCname());        tv2.setText(hmJson.get(position).getCcur());        return itemView;    }
}
--------------------------------------------------------------------------------------------

STEP-8 : JsonPOJO

----------------------------------------------------------------------------------------------

public class JsonPOJO {

    public JsonPOJO(String cname, String country_code, String ccur) {
        this.cname = cname;        this.ccur = ccur;        this.country_code = country_code;    }

    public String getCname() {
        return cname;    }

    public String getCcur() {
        return ccur;    }

    public String getCountry_code() {
        return country_code;    }

    String cname;    String country_code;    String ccur;}
----------------------------------------------------------------------------------------------------

STEP-9 : JsonConvertAdapter

-----------------------------------------------------------------------------------------------------

import android.app.ProgressDialog;import android.content.Context;import android.os.AsyncTask;import android.util.Log;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;
/** * Created by Divakar on 1/10/2017. */


public class JsonConvertAdapter extends AsyncTask<String, String, String> {

        Context context;        public static final String TAG=Package.getPackages().getClass().getName().toString();        String lineOfJson="";        private ProgressDialog progressDialog;        private String url1 = "http://192.168.1.16/CURRENCY/cu.php";
        public JsonConvertAdapter(Context context)
        {   this.context = context;   }

        @Override        protected void onPreExecute() {
            super.onPreExecute();            progressDialog = new ProgressDialog(context);            //progressDialog.setTitle("Product Image");            progressDialog.setMessage("Processing...");            progressDialog.setIndeterminate(true);            progressDialog.setCancelable(false);            // progressDialog.show();        }

        @Override        public String doInBackground(String... inParams)
        {
            /*String am = "2";            String fromc = "USD";            String toc = "INR";            */            String am = inParams[0];            String fromc = inParams[1];            String toc = inParams[2];
            try {
                URL url = new URL(url1);                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();                httpURLConnection.setRequestMethod("POST");                httpURLConnection.setDoOutput(true);                httpURLConnection.setDoInput(true);                OutputStream outputStream = httpURLConnection.getOutputStream();                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String post_data = URLEncoder.encode("amount","UTF-8")+"="+URLEncoder.encode(am, "UTF-8")+"&"                        +URLEncoder.encode("fromc", "UTF-8")+"="+URLEncoder.encode(fromc, "UTF-8")+"&"+
                        URLEncoder.encode("to", "UTF-8")+"="+URLEncoder.encode(toc, "UTF-8");
                bufferedWriter.write(post_data);                bufferedWriter.flush();                bufferedWriter.close();                outputStream.close();                InputStream inputStream = httpURLConnection.getInputStream();                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                lineOfJson = bufferedReader.readLine().toString();
                if(lineOfJson != null) {

                    return lineOfJson;                }

                bufferedReader.close();                inputStream.close();                httpURLConnection.disconnect();            }catch (MalformedURLException mue)
            {
                Log.e(TAG, "Error : "+mue);            }catch (IOException ioe)
            {
                Log.e(TAG,"Error : "+ioe);            }
            return  lineOfJson;        }

        @Override        protected void onPostExecute(String s) {
            super.onPostExecute(s);            // progressDialog.dismiss();        }
    }
----------------------------------------------------------------------------------------------------

STEP-10 : CountryJsonAdapter

-----------------------------------------------------------------------------------
import android.content.Context;import android.os.AsyncTask;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.io.IOException;import java.util.ArrayList;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;
/** * Created by Divakar on 6/5/2017. */
public class CountryJsonAdapter extends AsyncTask<String, String, ArrayList<JsonPOJO>>{

    Context mContext;    private static final String TAG = CountryJsonAdapter.class.getSimpleName();
    OkHttpClient client = new OkHttpClient();    CountryJsonAdapter(Context mContext) {
        this.mContext = mContext;    }

    @Override    protected ArrayList<JsonPOJO> doInBackground(String... params) {

        String url1 = "http://www.mycurrency.net/service/rates";
        String lineofjson = null;        try {
            lineofjson = run(url1);        } catch (IOException e) {
            e.printStackTrace();        }
        System.out.println(lineofjson);
        //  String json1 = lineofjson.substring(1, lineofjson.length()-1);
        return convertJSON(lineofjson);    }

    @Override    protected void onPostExecute(ArrayList<JsonPOJO> jsonPOJOs) {
        super.onPostExecute(jsonPOJOs);
    }

    // OkHttp getting JSON Data    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();        }
    }

    // CONVERT JSON TO ARRAYLIST    public ArrayList<JsonPOJO> convertJSON(String lineOfJson)
    {
        ArrayList<JsonPOJO> jsonAL = new ArrayList<>();        try {
            // JSONObject jsonObject1 = new JSONObject(lineOfJson);            JSONArray jsonArray1 = new JSONArray(lineOfJson);            for(int i = 0; i<jsonArray1.length(); i++)
            {
                JSONObject jsonObject2 = jsonArray1.getJSONObject(i);                String country = jsonObject2.getString("name");                String country_code = jsonObject2.getString("code");                String currency = jsonObject2.getString("currency_code");
                System.out.println(country);                System.out.println(currency);
                JsonPOJO jsonPOJO = new JsonPOJO(country, country_code, currency);                jsonAL.add(jsonPOJO);

            }

        } catch (JSONException e) {
            e.printStackTrace();        }
        return jsonAL;    }
}
-----------------------------------------------------------------------------------------

IMAGE -


























22

Wednesday, 31 May 2017

ButterKnife Fragment


Step - 1: App this library to App level gradle

compile 'com.jakewharton:butterknife:6.1.0'


Step - 2 : activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    android:background="#ffffff"    tools:context="cmsecomm.ecommerce.app.com.butterknife.MainActivity">
,   <fragment    android:name="cmsecomm.ecommerce.app.com.butterknife.PageFragment"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/id1"    /></LinearLayout>

Step - 3 : MainActivity.java

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Button;import android.widget.TextView;
import butterknife.ButterKnife;import butterknife.InjectView;import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {


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

    }
}

Step - 4 : fragment-page.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    android:background="#ffffff"    tools:context="cmsecomm.ecommerce.app.com.butterknife.MainActivity">
    <TextView        android:id="@+id/tv1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Hello World!"        android:textColor="#000000"        />    <Button        android:id="@+id/btn1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button1"        />    <Button        android:id="@+id/btn2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button2"        />    <Button        android:id="@+id/btn3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button3"        />
</LinearLayout>

Step - 5 : PageFragment.java

import butterknife.ButterKnife;import butterknife.InjectView;import butterknife.OnClick;
/** * Created by Divakar on 5/31/2017. */
public class PageFragment extends Fragment {

    @InjectView(R.id.tv1)
    TextView tv1;    @InjectView(R.id.btn1)
    Button b1;    @InjectView(R.id.btn2)
    Button b2;    @InjectView(R.id.btn3)
    Button b3;
    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View itemView = inflater.inflate(R.layout.fragment_page, container, false);
        ButterKnife.inject(this, itemView);
        tv1.setText("This is Fragment");
        return itemView;    }
    @OnClick(R.id.btn1)
    void buttonClick()
    {
        tv1.setText("Fragment-Button1");    }

    @OnClick({R.id.btn2, R.id.btn3})
    void performClick()
    {
        tv1.setText("Fragment-Button 2 & 3 mixed click");    }
}

ButterKnife Simple


Step - 1 : Add this library to gradle

compile 'com.jakewharton:butterknife:6.1.0'

Step - 2 : activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    android:background="#ffffff"    tools:context="cmsecomm.ecommerce.app.com.butterknife.MainActivity">
    <TextView        android:id="@+id/tv1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Hello World!"        android:textColor="#000000"        />    <Button        android:id="@+id/btn1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button1"        />    <Button        android:id="@+id/btn2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button2"        />    <Button        android:id="@+id/btn3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button3"        />
</LinearLayout>

Step - 3 : MainActivity.java

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Button;import android.widget.TextView;
import butterknife.ButterKnife;import butterknife.InjectView;import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.tv1)
    TextView tv1;    @InjectView(R.id.btn1)
    Button b1;    @InjectView(R.id.btn2)
    Button b2;    @InjectView(R.id.btn3)
    Button b3;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.inject(this);
        tv1.setText("New Auto Text");    }
    @OnClick(R.id.btn1)
    void buttonClick()
    {
        tv1.setText("Button1");    }

    @OnClick({R.id.btn2, R.id.btn3})
    void performClick()
    {
        tv1.setText("Button 2 & 3 mixed click");    }
}

Tuesday, 28 March 2017

Retrofit Library WITH OkHTTP - Login




Detail Description :  http://androidnoteblog.blogspot.in/2017/03/retrofit-library-with-okhttp.html



Step - 1 : App dependency to app level gradle.

 compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup:otto:1.3.8'
    compile 'com.google.code.gson:gson:2.6.2'

Step - 2 :  Add internet permission to AndroidManifest.xml

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

Step - 3 : activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    >
    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical"        android:id="@+id/loginLayout">
        <EditText            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:id="@+id/usernameInput"            android:hint="Username:"            android:text="admin"            />
        <EditText            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:id="@+id/passwordInput"            android:hint="Password:"            android:text="admin"            />
        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">
            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:id="@+id/loginButtonPost"                android:text="Login - Post"                android:layout_gravity="right"                android:layout_weight="1" />
            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:id="@+id/loginButtonGet"                android:text="Login - Get"                android:layout_weight="1" />
        </LinearLayout>
    </LinearLayout>
    <LinearLayout        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="fill_parent"        android:layout_below="@id/loginLayout">
        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/information"            android:layout_gravity="center_horizontal"            android:layout_marginTop="20dp" />
        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/extraInformation"            android:layout_gravity="center_horizontal"            android:layout_marginTop="20dp" />    </LinearLayout>
</RelativeLayout>

Step - 4 : MainActivity.java

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.method.PasswordTransformationMethod;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import com.squareup.otto.Bus;import com.squareup.otto.Subscribe;
public class MainActivity extends AppCompatActivity {

    private Communicator communicator;    private String username, password;    private EditText usernameET, passwordET;    private Button loginButtonPost, loginButtonGet;    private TextView information, extraInformation;    private final static String TAG = "MainActivity";    public static Bus bus;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        communicator = new Communicator();
        usernameET = (EditText)findViewById(R.id.usernameInput);        passwordET = (EditText)findViewById(R.id.passwordInput);        //This is used to hide the password's EditText characters. So we can avoid the different hint font.        passwordET.setTransformationMethod(new PasswordTransformationMethod());
        loginButtonPost = (Button)findViewById(R.id.loginButtonPost);        loginButtonPost.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                username = usernameET.getText().toString();                password = passwordET.getText().toString();                usePost(username, password);            }
        });
        loginButtonGet = (Button)findViewById(R.id.loginButtonGet);        loginButtonGet.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                username = usernameET.getText().toString();                password = passwordET.getText().toString();                useGet(username, password);            }
        });
        information = (TextView)findViewById(R.id.information);        extraInformation = (TextView)findViewById(R.id.extraInformation);    }

    private void usePost(String username, String password){
        communicator.loginPost(username, password);    }

    private void useGet(String username, String password){
        communicator.loginGet(username, password);    }

    @Subscribe    public void onServerEvent(ServerEvent serverEvent){
        Toast.makeText(this, ""+serverEvent.getServerResponse().getMessage(), Toast.LENGTH_SHORT).show();        if(serverEvent.getServerResponse().getUsername() != null){
            information.setText("Username: "+serverEvent.getServerResponse().getUsername() + " || Password: "+serverEvent.getServerResponse().getPassword());        }
        extraInformation.setText("" + serverEvent.getServerResponse().getMessage());    }

    @Subscribe    public void onErrorEvent(ErrorEvent errorEvent){
        Toast.makeText(this,""+errorEvent.getErrorMsg(),Toast.LENGTH_SHORT).show();    }

    @Override    public void onResume(){
        super.onResume();        BusProvider.getInstance().register(this);    }

    @Override    public void onPause(){
        super.onPause();        BusProvider.getInstance().unregister(this);    }

}

Step - 5 : BusProvider.java

import com.squareup.otto.Bus;
public class BusProvider {

    private static final Bus BUS = new Bus();
    public static Bus getInstance(){
        return BUS;    }

    public BusProvider(){}
}


Step - 6 :  Communicator.java

import android.util.Log;import okhttp3.OkHttpClient;import okhttp3.logging.HttpLoggingInterceptor;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;
public class Communicator {
    private static  final String TAG = "Communicator";    private static final String SERVER_URL = "http://192.168.1.102/retrofit_login/";    //private static final String SERVER_URL = "http://127.0.0.1/retrofit";
    public void loginPost(String username, String password){

        //Here a logging interceptor is created        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        //The logging interceptor will be added to the http client        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();        httpClient.addInterceptor(logging);
        //The Retrofit builder will have the client attached, in order to get connection logs        Retrofit retrofit = new Retrofit.Builder()
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(SERVER_URL)
                .build(); Interface service = retrofit.create(Interface.class);
        Call<ServerResponse> call = service.post("login",username,password);
        call.enqueue(new Callback<ServerResponse>() {
            @Override            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                BusProvider.getInstance().post(new ServerEvent(response.body()));                Log.e(TAG,"Success");            }

            @Override            public void onFailure(Call<ServerResponse> call, Throwable t) {
                // handle execution failures like no internet connectivity                BusProvider.getInstance().post(new ErrorEvent(-2,t.getMessage()));            }
        });    }

    public void loginGet(String username, String password){
        //Here a logging interceptor is created        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        //The logging interceptor will be added to the http client        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();        httpClient.addInterceptor(logging);
        //The Retrofit builder will have the client attached, in order to get connection logs        Retrofit retrofit = new Retrofit.Builder()
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(SERVER_URL)
                .build();
        Interface service = retrofit.create(Interface.class);
        Call<ServerResponse> call = service.get("login",username,password);
        call.enqueue(new Callback<ServerResponse>() {
            @Override            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                BusProvider.getInstance().post(new ServerEvent(response.body()));                Log.e(TAG,"Success");            }

            @Override            public void onFailure(Call<ServerResponse> call, Throwable t) {
                // handle execution failures like no internet connectivity                BusProvider.getInstance().post(new ErrorEvent(-2,t.getMessage()));            }
        });    }

}

Step - 7 : ErrorEvent.java

public class ErrorEvent {
    private int errorCode;    private String errorMsg;
    public ErrorEvent(int errorCode, String errorMsg) {
        this.errorCode = errorCode;        this.errorMsg = errorMsg;    }

    public int getErrorCode() {
        return errorCode;    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;    }

    public String getErrorMsg() {
        return errorMsg;    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;    }
}


Step - 8 : Create interface ( Interface.interface )

import retrofit2.Call;import retrofit2.http.Field;import retrofit2.http.FormUrlEncoded;import retrofit2.http.GET;import retrofit2.http.POST;import retrofit2.http.Query;
public interface Interface {

    //This method is used for "POST"    @FormUrlEncoded    @POST("http://192.168.1.102/retrofit_login/login_api.php")
    Call<ServerResponse> post(
            @Field("method") String method,            @Field("username") String username,            @Field("password") String password
    );
    //This method is used for "GET"    @GET("http://192.168.1.102/retrofit_login/login_api.php")
    Call<ServerResponse> get(
            @Query("method") String method,            @Query("username") String username,            @Query("password") String password
    );
}

Step - 9 : ServerEvent.java

public class ServerEvent {
    private ServerResponse serverResponse;
    public ServerEvent(ServerResponse serverResponse) {
        this.serverResponse = serverResponse;    }

    public ServerResponse getServerResponse() {
        return serverResponse;    }

    public void setServerResponse(ServerResponse serverResponse) {
        this.serverResponse = serverResponse;    }
}

Step - 10 : ServerResponse.java

import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class ServerResponse implements Serializable {
        @SerializedName("returned_username")
        private String username;        @SerializedName("returned_password")
        private String password;        @SerializedName("message")
        private String message;        @SerializedName("response_code")
        private int responseCode;
        public ServerResponse(String username, String password, String message, int responseCode){
            this.username = username;            this.password = password;            this.message = message;            this.responseCode = responseCode;        }

        public String getUsername() {
            return username;        }

        public String getPassword() {
            return password;        }

        public String getMessage() {
            return message;        }

    }

Step - 11 :  Save login_api.php in XAMPP/WAMP root directory.

login_api.php,

<?php
        //Post Method here        if(isset($_POST['method']) == 'login'){
        $username = $_POST['username'];        $password = $_POST['password'];
        if($username == "admin" && $password == "admin"){
        $response = array('returned_username' => "-admin-",        'returned_password' => "-admin-",        'message' => "Your credentials are so weak [USING_POST]!",        'response_code' => "1");        echo json_encode($response);
        }else{
        $response = array('response_code' => "-1",        'message' => "invalid username or password");        echo json_encode($response);        }
        }
        //Get Method here        else if(isset($_GET['method']) == 'login'){
        $username = $_GET['username'];        $password = $_GET['password'];
        if($username == "admin" && $password == "admin"){
        $response = array('returned_username' => "=admin=",        'returned_password' => "=admin=",        'message' => "Your credentials are so weak [USING_GET]!",        'response_code' => "1");        echo json_encode($response);        }else{
        $response = array('response_code' => "-1",        'message' => "invalid username or password");        echo json_encode($response);        }
        }

//If no method        else{
        $response = array('response_code' => "-2",        'message' => "invalid method");        echo json_encode($response);        }
        ?>


22

Monday, 27 March 2017

Piccasso Image Download to Storage



Piccasso WebLink : http://square.github.io/picasso/
Help Web -1 : https://code.tutsplus.com/tutorials/android-sdk-working-with-picasso--cms-22149

Step-1 : Add library to App level Gradle


compile 'com.squareup.picasso:picasso:2.5.2'

Step - 2 : Add permission to AndroidManifest.xml


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

Step-3 : activity_main.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" >
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
     />
</LinearLayout>

Step- 4 : MainAcivity.java



import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private ImageView mImageView;
    private String mURL = "http://www.allindiaflorist.com/imgs/arrangemen4.jpg";
    private String urls = "http://api.androidhive.info/images/sample.jpg";
    private String[] urlArray = {mURL, urls};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = (ImageView) findViewById(R.id.image);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Picasso.with(getApplicationContext()).load(mURL).into(mImageView);
        for (int i=0; i<urlArray.length; i++) {
            Picasso.with(getApplicationContext()).load(urlArray[i]).into(target);
        }
    }

    private Target target = new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    File folder = new File(MainActivity.this.getExternalFilesDir(null),  "/Picasso/");
                    if (!folder.exists()) {
                        if (!folder.mkdir()) {
                            Log.e("ERROR", "Cannot create a directory!");
                        } else {  folder.mkdir();   }
                    }

                    File[] fileName = {new File(folder, "one.jpg"), new File(folder, "two.jpg")};
                    for (int i=0; i<fileName.length; i++) {
                        if (!fileName[i].exists()) {
                            try {
                                fileName[i].createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                FileOutputStream outputStream = new FileOutputStream(String.valueOf(fileName[i]));
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                outputStream.close();

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

                }
            }).start();
        }
        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            Toast.makeText(getApplicationContext(),"Failed", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };



Description :




22.