AdButler on Android

AdButler is a powerful, easy-to-learn Ad Server that can meet your needs whether you are a publisher, and advertiser, or even a bit of both! Check us out at https://adbutler.com or learn more about our product at http://www.adbutlerhelp.com/home.

Mobile ad serving is a force that can help you monetize your app or optimize the value of your ad campaign. AdButler's user-friendly interface and blazing-fast ad delivery make serving ads as stress-free as possible. Combining the two is a recipe for success, and today I am going to teach you how to use AdButler's JSON API to take advantage of the power that mobile ad serving provides.

Using AdButler's JSON API for your mobile app is a breeze. The first step is to make an HTTP GET request to the URL given by your zone tag. Choose the 'JSON Ad API' option from Get Zone Tags.

You can make this request however you like, but the Volley library for Android makes these types of requests quick and painless. Since we are expecting a response in JSON format, use the JSONObjectRequest function from Volley. Here is an example of such a request:

        //Set up a new Volley request queue
        RequestQueue queue = Volley.newRequestQueue(this);

        //Define the request
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {

            //When the response comes in, this function is called
            @Override
            public void onResponse(JSONObject response) {
                callback.onSuccess(response);

            }
        }, new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError error){

            }

        });
        //Add the request to the Volley request queue
        queue.add(request);

The response comes back in JSON format which is easily parsed in both Android and iOS. An example JSON response from AdButler looks like this:

All the necessary information for the ad is in this JSON Object. To place the ad's image in your app, you need to download it first. The class below will download the image asynchronously (without blocking your app):

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView image;

    public DownloadImageTask(ImageView bmImage) {
        this.image = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {

        image.setImageBitmap(result);
    }
}

And you call this class like so:

//img is an ImageView and imgurl is the image_url taken from the JSON response
new DownloadImageTask(img).execute(imgurl);

*Note: If your ad has a third-party tracking pixel, or you have accupixel enabled, it is important to remember to download the images from these URLs as well. Placing these optional images in your app will ensure that your ads are tracking statistics up to your specifications.

Now, when a user clicks on the image, we want it to go to the correct destination. To do this, we set up a Click Listener that opens the user's browser when the image is clicked.

//Set up the new Click Listener
img.setOnClickListener(new View.OnClickListener() {

    //When the image is clicked, this function is called
     public void onClick(View view) {

        //clickurl is the redirect_url from the JSON response
         openWebURL(clickurl);
    }
});

You are now displaying an ad on your mobile app!

Below is an example of an app that with a button that, when pressed, displays an ad. It is just the Java code, so to get this to work, you have to make sure to edit your content_main.xml so that your app displays the images and button.

As well, there are some reference links at the bottom of the page to help you with setting up Volley, and parsing JSON Objects in Android.

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    //Replace this string with the URL provided in the JSON ad tag.
    final String url = "http://servedbyadbutler.com/adserve/;ID=xxxxxx;size=300x250;setID=xxxxx;type=json;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getJSONObjectAndPlaceAd();
            }
        });

    }

    public void getJSONObjectAndPlaceAd(){

        //Set up new Volley request queue
        RequestQueue queue = Volley.newRequestQueue(this);

        //Define the request
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    //If the response was successful, place the ad on the page.
                    if (response.getString("status").equals("SUCCESS")) {

                        //Get the placement info from the JSON response, specifically the redirect URL and image URL
                        JSONObject placement = response.getJSONObject("placements").getJSONObject("placement_1");
                        String imgurl = placement.getString("image_url");
                        final String clickurl = placement.getString("redirect_url");
                        String trackingurl = placement.getString("accupixel_url");

                        //Download the image and tracking pixel to place in the app
                        ImageView img = (ImageView) findViewById(R.id.imageView);
                        ImageView accupixel = (ImageView) findViewById(R.id.accupixel);
                        new DownloadImageTask(img).execute(imgurl);
                        new DownloadImageTask(accupixel).execute(trackingurl);

                        //Set up the new Click Listener so the image redirects when clicked
                        img.setOnClickListener(new View.OnClickListener() {

                            //When the image is clicked, this function is called
                            public void onClick(View view) {

                                //clickurl is the redirect_url from the JSON response
                                openWebURL(clickurl);
                            }
                        });
                    }

                }catch(JSONException e){
                    //Handle any JSON errors how you'd like
                    System.err.println(e);
                }

            }
        }, new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError error){

            }

        });
        //Add the request to the Volley request queue
        queue.add(request);
    }

    //Redirect to the specified URL
    public void openWebURL(String url){
        Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(browse);
    }

}

//This class handles the image download asynchronously
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView image;

    public DownloadImageTask(ImageView bmImage) {
        this.image = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {

        image.setImageBitmap(result);
    }
}

Download and Include Volley for Android URL Requests: http://www.technoburgh.com/android/android-studio-volley/

Sending Requests with Volley: http://developer.android.com/training/volley/simple.html

JSON Parsing in Android: http://www.json.org/javadoc/org/json/JSONObject.html