Browse Category: Android

Abstract class to get a address from current location in Android

public abstract class ReverseGeocoderTask extends AsyncTask<Void, Void, String> {
    private static final String TAG = "ReverseGeocoder";
    private String value = "Checking your location...";

    public abstract void onAddressFound(String address);

    private float mLat;
    private float mLng;
    private Activity mContext;

    public ReverseGeocoderTask(Activity context, Location location) {
        mContext = context;
        mLat = (float) location.getLatitude();
        mLng = (float) location.getLongitude();

    protected void onPreExecute() {
        value = "Searching for address...";

    protected String doInBackground(Void... params) {
        try {
            List<Address> addressList =
                    getFromLocation(mLat, mLng, 1);
            StringBuilder sb = new StringBuilder();
            for (Address addr : addressList) {
                int index = addr.getMaxAddressLineIndex();

            value = sb.toString();
//          Logger.logger("Address Address    " + value);
        } catch (Exception ex) {

            Utilities.showToast(mContext,"Oops! There was an error.Please try to search your location again.");
            value = "Type your location here...";
//            Log.e(TAG, "Geocoder exception: ", ex);
        return value;

    protected void onPostExecute(String location) {

    public static List<Address> getFromLocation(double lat, double lng, int maxResult) {

        List<Address> retList = null;
        String address = String.format(Locale.getDefault(), "$f,%2$f&language=" + Locale.getDefault(), lat, lng);
        URL myurl;
        try {
            myurl = new URL(address);
//            Logger.logger("myurl.......URl...=  ", myurl.toString());
            HttpURLConnection urlConnection = (HttpURLConnection) myurl.openConnection();
            InputStream is = urlConnection.getInputStream();
            if (is != null) {
                int responseCode = urlConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader responseReader = new BufferedReader(new InputStreamReader(is));
                    String responseLine;
                    StringBuilder stringBuilder = new StringBuilder();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is));
                    while ((responseLine = responseReader.readLine()) != null) {

//                    Logger.logger("stringBuilder.......stringBuilder...=  ", stringBuilder.toString());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject = new JSONObject(stringBuilder.toString());

                    retList = new ArrayList<>();

                    Address addr = new Address(Locale.getDefault());
                    if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
                        JSONArray results = jsonObject.getJSONArray("results");
//                for (int i = 0; i < results.length(); i++) {
                        JSONObject result = results.getJSONObject(0);

                        String indiStr = result.getString("formatted_address");
//                        Logger.logger("indiStr   " + indiStr);

                        addr.setAddressLine(0, indiStr);

//                }
//                        Logger.logger("retList   " + retList);
                    } else {
//                        throw new IllegalStateException("Method failed: " + response.getStatusLine());
        } catch (IOException | JSONException e) {
        return retList;


Volley Library to make network connection from Android App

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Some of them are

1. Effective request cache and memory management
2. Cancelling the requests

To use volley library just make below changes in your build.gradle file:

dependencies {
    compile 'com.mcxiaoke.volley:library:1.0.17'

Now add below code to make network calls

StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            public void onResponse(String response) {
               //get response 
        new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) { 
        }) {
    protected Map<String, String> getParams() {
           // send parameters for post
        return map;


To set connection timeout add below code:
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
RequestQueue requestQueue = Volley.newRequestQueue(context);

Make future payment using Braintree payment gateway

This tutorial is for those who are developing a mobile application and they want to charge a customer(one or more time) in future. In this tutorial I am going to explain backend functionality in details.

Most of the time we need charge to  customer  in future. Some developers may store details in the database but this is not the best way when it comes to security. Fortunately this feature is provided by braintree and stripe payment gateways. Following tutorial will explain you how we can use braintree API.

Before we start a tutorial make sure that you have a braintree(Sandbox/Production) account, if you don’t have an account  you can open your braintree sandbox account from here Sandbox Account. Mobile developers need to install braintree provided sdk from here Mobile SDK
Braintree payment screen

Once you installed SDK successfully you can see the above screen and fields like card Number, Expiration Date and CVV Number which is provided by braintree you don’t need to do any code for that.

If you using sandbox account enter following Card details for testing purpose.

Sandbox Card Number: 4242 4242 4242 4242

Card Exp: Any future expiry month/Year

CVV: 123

When user click “Buy Now” button braintree SDK returns you paymentMethodNonce .  What you’ll do next step. Simply you’ll send paymentMethodNonce to your server through webservice.

Now the actual backend functionality start here.

Suppose you are sending the parameter paymentMethodNonce to the API

In add_card_token.php i will use the method provided by braintree (make sure you have downloaded PHP braintree library if not then click here)


require_once ‘lib/Braintree.php’; //installed braintree php library and include over here





$paymentMethodNonce = $_POST[‘paymentMethodNonce ‘];//Getting parameters from mobile dev

$result = Braintree_Customer::create( array( ‘firstName’ => ‘abc’, ‘lastName’ => ‘efg’, ‘company’ => ‘Nanostuffs’, ‘paymentMethodNonce’ => $paymentMethodNonce ));

$customerid = $result->customer->id; //Store this info into the database

$card_token = $result->customer->paymentMethods[0]->token;//Store this info into the database


The method (Braintree_Customer::create) will returns you all the basic information about the card like expiry, last four…

You will get customer id $result->customer->id and card_token in response $result->customer->paymentMethods[0]->token

You will store this information into the database for that particular customer.

Great, now you are ready to charge a customer in future anytime. Suppose i want to charge that customer now i will use the following method.


require_once ‘lib/Braintree.php’; //installed braintree php library and include over here






$result = Braintree_Transaction::sale(array(  ‘amount’ => ‘100’,

‘paymentMethodToken’ => $customer_id,

‘options’ => [ ‘submitForSettlement’ => True  ] )


if($result->success) {

$transactionId = $result->transaction->id;


$err = ”;

foreach($result->errors->deepAll() AS $error) { $err.= $error->message.” “; }

echo $err;


}catch(Exception $e)



Check and parse proper response returned by braintree. You have charged to the customer successfully. If you run the same method again you can see the charge successfully. Without entering user card details again.

You can achieve this using any sever side langauge. I am familiar with PHP only.

Let us know if this tutorial really help you 🙂

Creating Custom Apex REST APIs with

Suppose we want to expose Opportunity object through Rest Web Service.

Step 1 : Create a class like below

global with sharing class RESTOppController
global static List<Opportunity> getOpenOpportunities()
String OpportunityName = RestContext.request.params.get(‘OpportunityName’);
Opportunity opp = [ Select ID, Name, Amount from Opportunity where Name = :OpportunityName];
List<Opportunity> OppList = [SELECT Id, CloseDate,StageName, Type,  LeadSource from Opportunity WHERE Name =: Opp.Name];
return OppList;

Step 2: Create sites. It  enable you to create public websites and applications. Under App Setup expand Develop and click Sites.

Step 3: Choose a domain name. Ensure it is available, click the checkbox, then click Register My Domain.

Step 4: Once your site is registered click the New button.

Step 5:    Give yourself a Site LabelSite Name, and choose an Active Site Home Page. Since no one will use this site as a website I’ve chosen FileNotFound. Click the Save button.

Step 6: By default the site is not active. Click the Activate button or else you will not be able to access your APIs.

Step 7: Next we have to grant anonymous access to our Apex REST API. Click thePublic Access Settings button.

Step 8: Scroll down the Standard Object Permissions and check all checkbox of Opportunity and click on Save button.

Step 9: Scroll down to Enabled Apex Class Access and click the Edit button. Select the RESTOppController and click the Add button. Click Save.

Step 10: Get the url from your site that you have created and put that url to the url bar of your brouser. The url looks like

Use of basic Authentication for post URL

To mark all url in application authenticate, use of basic authentication could good option.

In Below example I used Username and Password to generate Authentication header .


String authentication = editusername.getText().toString().trim()+”:”+editpassword.getText().toString().trim();

String authHeader =Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);


Use this “authHeader”  in every call of Url…like this,

httpPut.setHeader(“Authorization”, “Basic “+””+authHeader);


httpPost.addHeader(“Authorization”, “Basic “+””+authHeader);

Rotate the Activity.

To rotate Activity around it’s X-axis use Activity Switcher class.

For Animation Out:

ActivitySwitcher.animationOut(findViewById(, getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() {

@Override public void onAnimationFinished() {





For Animation In:

ActivitySwitcher.animationIn(findViewById(, getWindowManager());


Communication between Bluetooth devices

I had used this communication to get the surrounding temperature, but we can also use this to develop chat room which will be offline.

BluetoothSPP bt; //Bluetooth Socket

bt = new BluetoothSPP(this); //initilisation

// check weather Bluetooth is on/off


if (!bt.isBluetoothEnabled()) {

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT);


else {











Toast.makeText(getApplicationContext() , “Bluetooth is not available” , Toast.LENGTH_SHORT).show();



bt.setBluetoothConnectionListener(new BluetoothConnectionListener() {

public void onDeviceDisconnected() {

//do something if device get disconnected


public void onDeviceConnectionFailed() {

//do something if device connection get failed


public void onDeviceConnected(String name, String address) {

//  do something if device get connected

// name is the name of connected  device  and address is the unique is of bluetooth



bt.setOnDataReceivedListener(new OnDataReceivedListener()


public void onDataReceived(byte[] data,String message)


// when any message is get received




Change color of image to transparent

CGImageRef rawImageRef = image.CGImage;

const double colorMasking[6] = { 0, 0, 0, 0, 0, 0 };



CGImageRef maskedImageRef =  CGImageCreateWithMaskingColors(rawImageRef, colorMasking);


CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, image.size.height);

CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);



CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), maskedImageRef);

UIImage *result = UIGraphicsGetImageFromCurrentImageContext();




Merge two images by retaining opacity of Image



CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, 0, topImage.size.height);

CGContextScaleCTM(context, 1.0, -1.0);

CGRect rect = CGRectMake(0, 0, topImage.size.width, topImage.size.height);

// draw black background to preserve color of transparent pixels

CGContextSetBlendMode(context, kCGBlendModeNormal);

[[UIColor whiteColor] setFill];

CGContextFillRect(context, rect);

// draw original image

CGContextSetBlendMode(context, kCGBlendModeNormal);

CGContextDrawImage(context, rect, bottomImage.CGImage);

// tint image (loosing alpha) – the luminosity of the original image is preserved

CGContextSetBlendMode(context, kCGBlendModeDarken);

[[UIColor colorWithPatternImage:topImage] setFill];

CGContextFillRect(context, rect);

// mask by alpha values of original image

CGContextSetBlendMode(context, kCGBlendModeDestinationIn);

CGContextDrawImage(context, rect, topImage.CGImage);

// image drawing code here

UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();