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

No comments:

Post a Comment