Send SMS Using SMS Gateway from Android

In Android, you can use SmsManager API or devices Built-in application to send SMS’s. Therefore in this tutorial, we shows how to send SMS message using SMS Gateway from android. However Some times it’s important to inform user about changes made to there account by email or sms. Such as verification codes,conformations etc, please let me present some interesting facts in this topic.

At this point about 5.1 billion out of the 6.8 billion people on Earth own a mobile phone – that’s a huge.

There are twice as many active SMS users in the world than active users of email.

On average, it takes 9 minutes for someone to respond to an SMS (by comparison, the response time in case of e-mail is 90 minutes).

Around 98 per cent of all messages are opened, but only 20 per cent of emails are looked at.

 

Android

Of course first is the android part, it transmit address of the recipient and message to be send. In order to transmit network data we are  using volley. And also the response is received by volley network library. As a matter of fact internet permission is required for this project.

Server

In fact way2sms don’t provide an official api for users. Still there are several api’s available unofficially. As a result of googling found a suitable api. Then modified it to work with android. However you can use wamp or any other free hosting providers as server. In the same way api working and it’s integration is explained below.

Introduction

Accordingly there is a lot of free Sms sending web portals available on the internet. Therefore people use them to send bulk and nonbulk Short messages without any charge. Still Way2Sms is one of the No.1 SMS Portal on the World Wide Web almost 1 million users were registered with them and send millions of message per day. Hence you are going to learn about the Way2Sms Php API Script Integration in an android app in this article.

How Way2Sms API  Script Works:

Consequently by integrating the Way2Sms Php API Script in your app, Your can send  SMS Directly through your app. You are never redirected to Way2Sms official site for login or another purpose. Because every action will take place through your server itself. You can also modify the script design like yours . Because the code was developed using PHP and it was too simple.

How to Integrate Way2Sms PHP API Script:

In fact it’s very easy to integrate the PHP API script on your app or website. In order to do this, you must have a Php Enabled Server (Cpanel). If you don’t have a PHP Supported Server, then create a free A/c on any of the site that listed on the linked page: Link Here

 

After creating an A/c or log in to your Existing Cpanel A/c, Do the following steps and procedure to integrate the  API script on your website. Or you can use wamp instead.

Above all first Download the script from here: Download,

Then Go to File-Browser of your Cpanel A/c & Create a “New Folder” name “androidsms”.

Afterward Upload the “12sms.rar” Downloaded the file to the “androidsms”.

Next Extract the “12sms.rar” File.

Run like: “http://example.com/androidsms/sms.php”.

You are Done.

SMS-Gateway

Accordingly a SMS-Gateway allows a computer to send or receive Short Message Service transmissions to or from a telecommunications network. Most messages are eventually routed into the mobile phone networks. In fact it’s able to send the messages coming from your Android application through HTTP to the SMSC (Short Message Service Center) of the Mobile Service Provider via SMPP IP SMS connection or a GSM modem. However the SMSC is a network element in the mobile telephone network that stores, forwards, converts and delivers SMS messages. Still to be able to send messages using HTTP, you will need an SMS Gateway that has a built-in webserver. In conclusion it allows you to send text messages from your application by calling an URL (HTTP Get) or using the HTTP Post method.

 

Sms.php

In addition below is the modified php script for sending message. It also require other script’s from the rar file.

<?php

include('func.php');
error_reporting(0);
set_time_limit(0);
$ser="http://site24.way2sms.com/";
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$login=$ser."Login1.action";
// * Reciving Username of Way2sms A/c from Html form //
$uid="youruserid";
// * Reciving Password of Way2sms A/c from Html form //
$pwd="yourpassword";//input($_REQUEST['pwd']);
// * To whome the message send to 
$to=$_POST['to'];
// * Message to be sended //
$msg=$_POST['message'];

$jsonData      = array();
$jsonTempData  = array();

if(!$to)
{ $to=$uid; }
if(!$msg)
{ $msg=rword(5).rword(5).rword(5).rword(5).rword(5); }
$captcha=input($_REQUEST['captcha']);
flush();
if($uid && $pwd)
{
$ibal="0";
$sbal="0";
$lhtml="0";
$shtml="0";
$khtml="0";
$qhtml="0";
$fhtml="0";
$te="0";
flush();

$loginpost="gval=&username=".$uid."&password=".$pwd."&Login=Login";

$ch = curl_init();
$lhtml=post($login,$loginpost,$ch,$ckfile);

if(stristr($lhtml,'Location: '.$ser.'vem.action') || stristr($lhtml,'Location: '.$ser.'MainView.action') || stristr($lhtml,'Location: '.$ser.'ebrdg.action'))
{
preg_match("/~(.*?);/i",$lhtml,$id);
$id=$id['1'];
if(!$id)
{
    goto end;
}
goto bal;
}
elseif(stristr($lhtml,'Location: http://site2.way2sms.com/entry'))
{
    goto end;
}
else
{goto end;
}
bal:
$msg=urlencode($msg);
$main=$ser."smstoss.action";
$ref=$ser."sendSMS?Token=".$id;
$conf=$ser."smscofirm.action?SentMessage=".$msg."&Token=".$id."&status=0";

$post="ssaction=ss&Token=".$id."&mobile=".$to."&message=".$msg."&Send=Send Sms&msgLen=".strlen($msg);
$mhtml=post($main,$post,$ch,$ckfile,$proxy,$ref);
if(stristr($mhtml,'smscofirm.action?SentMessage='))
// * Message Sended Sucessfull Message//
{
    $jsonTempData['sms']    ="Message send";
}   else
// * Login Faild or SMS Send Error Message 1//
{
    $jsonTempData['sms']   ="Error message 1";
}
    curl_close($ch);
end:
flush();
}
$jsonData[]=$jsonTempData;

$outputArr['check'] = $jsonData;
// Encode Array To JSON Data
print_r( json_encode($outputArr));

?>

 

MainActivity.java

Class file contain the sending of information  number and message.

public class MainActivity extends AppCompatActivity {
private EditText editTextTo,editTextMessage;
    RelativeLayout activity_main;

    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity_main=(RelativeLayout)findViewById(R.id.activity_main);
        editTextTo=(EditText)findViewById(R.id.editTextTo);
        editTextMessage=(EditText)findViewById(R.id.editTextMessage);
        requestQueue = Volley.newRequestQueue(this);
    }

    public void OnClickButton(View view){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

        if(editTextTo.getText().toString().isEmpty()){
            Snack("Number is empty");
        }else if(editTextTo.getText().length()!=10){
            Snack("Check the number");
        }else if(editTextMessage.getText().toString().isEmpty()){
            Snack("Message is empty");
        }else{
            SendSms(editTextTo.getText().toString(),editTextMessage.getText().toString());
        }
    }


    public void Snack(String message){
        Snackbar.make(activity_main, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
    }

    public void SendSms(final String to, final String message) {

        StringRequest menuRequest = new StringRequest(Request.Method.POST,"http://example.com/androidsms/sms.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonResponse = new JSONObject(response).getJSONArray("check");

                            int i = jsonResponse.length();
                            for(int j=0;j<i;j++){
                                JSONObject jsonChildNode = jsonResponse.getJSONObject(j);
                                Snack(jsonChildNode.optString("sms").toString());

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("Json",e.getMessage());
                            Snack("Json " + e.getMessage());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        Snack("Volley " + error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("to",to);
                params.put("message",message);
                return params;
            }
        };
        requestQueue.add(menuRequest);
    }

}

 

Incidentally here is the full code for android: Download.

Turing Your WordPress site into an android App

Turn your WordPress site into a native android app. Certainly not talking about creating a webview and loading an URL with it. In conclusion almost all android apps for website’s are URL loaded inside a webview. Although the webview is present here but it’s different.Let me explain.Don’t have to,let me show it.



Download full code here

In fact this video is sufficient explanation. However for this project we are using an actual website, yes this website. Hence turning this site into an android app. So let’s begin, Mainly this project is divided in to three.

  1. WordPress part.
  2. Web-service Part.
  3. Android part.

WordPress Part

In the first place start by installing a plugin for Accelerated Mobile Pages (AMP), i am using this one. Then after installing the plugin you can check your amp url. As a result normal url for a post is “www.yourwebsite.com/post/” and it’s amp url is “www.yourwebsite.com/post/amp/”. Keep it in mind we will be using it later.

Web-service Part

In addition to WordPress part this gets posts details from your database to android. Since it’s the sole purpose of this part. While only focus of this projects are posts. You can modify it as you like, either posts or pages even both. On with the code, Like my all other posts this web-service is also written in php. While WordPress is written using php as the scripting language. Therefore making it much more practical to use php. Create a folder in your public_html so we can access it like this “www.yourwebsite.com/yourfolder/webservice.php”.

However some of the things are gathered using WordPress functions. Especially relevant things like database name password thumbnail etc. So sensitive information’s are therefore hidden. Another interesting thing is that this code is universal just copy  and use. Also it work’s with any WordPress websites.

webservice.php

<?php
 /*
 * Post Template
   Used to call webservices
   Plugin Name: Android App logicchip
   Plugin URI: https://logicchip.com
   Description: A plugin for creating an android app of your site with realtime notifiaction and much more. 
   For more information please visit out site the link is below. #happy coding !
   Version: 1.0
   Author: Mr. Akhil Ashok
   Author URI: https://logicchip.com
   License: GPL2
   Email :akhilashok123@gmail.com,info@logicchip.com
   */
ini_set("memory_limit","128M");
 
// To load wordpress functions ,include file wp-load.php which is in root.
$base_dir = dirname(dirname(__FILE__));
require_once($base_dir."/wp-load.php");
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
if ($conn->connect_error) {
  //die("Connection failed: " . $conn->connect_error);
} else{
//echo "Connected successfully "."<br />\r\n";
}

$jsonDataBack  = array();

 $sql="SELECT wp_posts.ID,wp_posts.post_author,wp_posts.post_modified,wp_posts.guid,wp_users.display_name FROM wp_posts INNER JOIN wp_users 
 WHERE  wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' AND wp_users.ID = wp_posts.post_author ORDER BY wp_posts.post_date DESC ";

$result = $conn->query($sql);

    if ($result->num_rows > 0) {
        for ($x=0; $row = $result->fetch_assoc(); $x++) {
        $jTempData  = array();
        $jTempData['id']=$row["ID"];
        $jTempData['author']=$row["display_name"];
        $jTempData['name']=get_the_title($row["ID"]);       
        $jTempData['time']=$row["post_modified"];
        //$jTempData['link']=$row["guid"];
        $jTempData['link']=get_permalink($row["ID"]);
    
        if ( has_post_thumbnail($row["ID"])) {
        $jTempData['image']=$post_thumbnail_id = wp_get_attachment_url(get_post_thumbnail_id( $row["ID"] ));
            }else{
        $jTempData['image']="none";
            }
        setup_postdata($row["ID"]); 
        $categories = get_the_category($row["ID"]);
            if ( ! empty( $categories ) ) {  
        $jTempData['category']=esc_html( $categories[0]->name );
            }else{
        $jTempData['category']="none";      
            }
        $jTempData['content']=strip_tags(get_the_excerpt( $row["ID"]));
        $jsonDataBack[$x]=$jTempData;
            }
    }else{
        $jTempData  = array();
        $jTempData['id']="0";
        $jTempData['name']="none";
        $jTempData['link']="none";
        $jTempData['time']="none";
        $jTempData['content']="none";
        $jTempData['author']="none";
        $jTempData['image']="none";
        $jTempData['category']="none";
        $jsonDataBack[0]=$jTempData;
            }
$conn->close();
$outputArray['for_post'] = $jsonDataBack;
print_r( json_encode($outputArray));
?>



Android Part

Finally, Android part include fetching the information provided by the web-service. However the received information has a pattern and it’s repeating. Therefore we need to create a type for pattern and an adapter for repeating part. Also a list for displaying the adapter. Finally activity for reading the post.

Type

All the information received are of string type so it’s easy to work with. Class file for setting and getting information in this case string value’s. Another way is you can just sent it directly to the adapter, by using type complexity of the code is reduced.

WordPressType.java
public class WordPressType {

    String response_id,response_name,response_link,response_time,response_content,response_author,response_image,response_category;
    public WordPressType(){}

    public WordPressType(String response_id, String response_name, String response_link, String response_time, String response_content, String
    response_author, String response_image, String response_category){
        this.response_id=response_id;
        this.response_name=response_name;
        this.response_link=response_link;
        this.response_time=response_time;
        this.response_content=response_content;
        this.response_author=response_author;
        this.response_image=response_image;
        this.response_category=response_category;
    }
// in order to get string value
    public String getResponse_id(){return this.response_id;}
    public String getResponse_name(){return this.response_name;}
    public String getResponse_link(){return this.response_link;}
    public String getResponse_time(){return this.response_time;}
    public String getResponse_content(){return this.response_content;}
    public String getResponse_author(){return this.response_author;}
    public String getResponse_image(){return this.response_image;}
    public String getResponse_category(){return this.response_category;}
// in order to set string value
    public void setResponse_id(String response_id){this.response_id=response_id;}
    public void setResponse_name(String response_name){this.response_name=response_name;}
    public void setResponse_link(String response_link){this.response_link=response_link;}
    public void setResponse_time(String response_time){this.response_time=response_time;}
    public void setResponse_content(String response_content){this.response_content=response_content;}
    public void setResponse_author(String response_author){this.response_author=response_author;}
    public void setResponse_image(String response_image){this.response_image=response_image;}
  public void setResponse_category(String response_category){this.response_category=response_category;}
}

Before creating the adapter, See the images in the below image. Another class is created for caching those images to avoid using up the resources.

BitmapCache.java
public class BitmapCache extends LruCache<String, Bitmap> implements ImageCache {

    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        return cacheSize;
    }

    public BitmapCache(){
        this(getDefaultLruCacheSize());
    }

    public BitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

 

Adapter

So the adapter extents RecyclerView.Adapter and it’s placed inside the RecyclerView that’s the list. Like any adapter both xml and java part is required. CardView looks cool so it’s created with card view.

wordpress_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:elevation="5dp"
    app:cardElevation="5dp">
// in order for getting the image 
    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/idForImage"
        android:layout_gravity="top"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:src="@mipmap/ic_launcher"/>
    <View

        android:layout_marginTop="82dp"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:alpha=".7"
        android:background="@color/colorPrimaryText">

    </View>

    <LinearLayout
        android:layout_marginTop="80dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


        <TextView
            android:maxLines="1"
            android:id="@+id/idForName"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="16dp"
            android:textColor="@color/colorIcons"
            android:gravity="left"
            android:textSize="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Management Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs This is my web site, so do not override; let my WebView load the page"/>
          
        <TextView
            android:id="@+id/idForContent"
            android:layout_marginLeft="16dp"
            android:textColor="@color/colorDivider"
            android:maxLines="3"
            android:textAlignment="inherit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Management Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs This is my web site, so do not override; let my WebView load the page"/>
        <LinearLayout
            android:layout_marginLeft="16dp"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_weight="1"
                android:layout_gravity="left"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <TextView
                    android:layout_weight="1"
                    android:maxLines="1"
                    android:id="@+id/idForTime"
                    android:gravity="left"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Event Management Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs This is my web site, so do not override; let my WebView load the page"/>
                <TextView
                    android:layout_weight="1"
                    android:maxLines="1"
                    android:id="@+id/idForAuthor"
                    android:gravity="left"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Event Management Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs This is my web site, so do not override; let my WebView load the page"/>
            </LinearLayout>
            <LinearLayout
                android:layout_weight="1"
                android:layout_gravity="right"
                android:gravity="right"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <Button
                    android:id="@+id/idForCategory"
                    android:textStyle="bold"
                    style="@style/Widget.AppCompat.Button.Borderless"
                    android:textColor="@color/colorAccent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Event Management Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs This is my web site, so do not override; let my WebView load the page"/>
            </LinearLayout>


        </LinearLayout>

    </LinearLayout>


</android.support.v7.widget.CardView>

Errors are common while coding, if  “com.android.volley.toolbox.NetworkImageView” showing an error include volley in your dependencies .

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:palette-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
}
AdapterForWordPress.java

So the adapter contain ((WordPress)context).LoadPostView (); , because adapter can’t directly call parent activity methods. However LoadPostView() is the method and WordPress is the parent activity.

public class AdapterForWordPress extends RecyclerView.Adapter<AdapterForWordPress.ViewHolder>{
        private Activity context;
        private ArrayList<WordPressType> typeForPosts;
        private RequestQueue mRequestQueue;
        private ImageLoader mImageLoader;

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
            // each data item is just a string in this case
            TextView idForName,idForContent,idForTime,idForAuthor;
            Button idForCategory;
            NetworkImageView idForImage;

            public ViewHolder(View v) {
                super(v);
                idForName=(TextView)v.findViewById(R.id.idForName);
                idForContent=(TextView)v.findViewById(R.id.idForContent);
                idForTime=(TextView)v.findViewById(R.id.idForTime);
                idForAuthor=(TextView)v.findViewById(R.id.idForAuthor);
                idForCategory=(Button) v.findViewById(R.id.idForCategory);
                idForImage=(NetworkImageView) v.findViewById(R.id.idForImage);
                v.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                ((WordPress)context).LoadPostView(typeForPosts.get(getAdapterPosition()).getResponse_link().toString());
            }
        }

        public  AdapterForWordPress(Activity context,ArrayList<WordPressType> typeForPosts){
            this.context=context;
            this.typeForPosts = typeForPosts;
        }

        @Override
        public AdapterForWordPress.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // create a new view
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.wordpress_layout, parent, false);
            // set the view's size, margins, paddings and layout parameters
            ViewHolder vh = new ViewHolder(view);
            return vh;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
//each data is inserted
             holder.idForName.setText(typeForPosts.get(position).getResponse_name().toString());
             holder.idForContent.setText(typeForPosts.get(position).getResponse_content().toString());
             holder.idForAuthor.setText(typeForPosts.get(position).getResponse_author().toString());
             holder.idForCategory.setText(typeForPosts.get(position).getResponse_category().toString());
             holder.idForImage.setImageUrl(typeForPosts.get(position).getResponse_image(), getImageLoader());

            try {
                DateFormat inputFirstTime = new SimpleDateFormat(Constants.TEMPLATE_FOR_TIME);
                DateFormat inputSecondTime = new SimpleDateFormat(Constants.TEMPLATE_FOR_TIME);
                Date dateOne = new Date();

                Date dateTwo = inputFirstTime.parse(inputSecondTime.format(dateOne)+" 00:00:00");
                Date dateThree = inputFirstTime.parse(typeForPosts.get(position).getResponse_time().toString());

                Calendar calenderOne = Calendar.getInstance();
                calenderOne.setTime(dateThree);

                int monthOne = calenderOne.get(Calendar.MONTH);
                String month = getMonthForInt(monthOne);
                int hour =calenderOne.get(Calendar.HOUR);
                int day  = calenderOne.get(Calendar.DAY_OF_MONTH);
                int year = calenderOne.get(Calendar.YEAR);

                if(dateTwo.compareTo(dateThree)>0){
                    holder.idForTime.setText(year+" "+month+" "+day);
                }else if(dateTwo.compareTo(dateThree)<0){
                    holder.idForTime.setText("Tomorrow "+year+" "+month+" "+day+" "+hour);
                }else if(dateTwo.compareTo(dateThree)==0) {
                    //It's today not possible
                    holder.idForTime.setText("Today "+year+" "+month+" "+day+" "+hour);
                }else {
                    //How to get here ?
                    holder.idForTime.setText("Error "+year+" "+month+" "+day+" "+hour);
                }

            }catch (Exception e){
                ((WordPress)context).SnackBarMessage("Exception with date");
            }

        }

        @Override
        public int getItemCount() {
            return typeForPosts.size();
        }



//month in string from number
    public String getMonthForInt(int num) {
        String month = "wrong";
        DateFormatSymbols dfs = new DateFormatSymbols();
        String[] months = dfs.getMonths();
        if (num >= 0 && num <= 11 ) {
            month = months[num];
        }
        return month;
    }

//for requesting image file for network imageview
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }
        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,new BitmapCache());
        }
        return this.mImageLoader;
    }

    }

Parent activity

So the Parent activity contains SwipeRefreshLayout + NestedScrollView + RecyclerView. As a result of combining this, user interface is more material design. However this includes swipe refresh option auto hiding of action bar, and CallingPage is the web-service method. Retrieved web-service information is changed to type and that is place inside an array-list is passed to adapter. Another method LoadPostView is for the launching activity to read the post along with the link of selected post.

public class WordPress extends AppCompatActivity {
    private RecyclerView recycleViewWordPress;
    private RecyclerView.Adapter mAdapter;
    private RequestQueue queue;
    private ArrayList<WordPressType> typeForPosts;
    private SwipeRefreshLayout swipeRefreshLayout;
    private CoordinatorLayout coordinatorLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wordpress);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        coordinatorLayout=(CoordinatorLayout)findViewById(R.id.coordinatorLayout);
        swipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.swipeRefreshLayout);
        recycleViewWordPress=(RecyclerView)findViewById(R.id.recycleViewWordPress);
        recycleViewWordPress.setHasFixedSize(true);
        recycleViewWordPress.setLayoutManager(new LinearLayoutManager(this));
        // specify an adapter (see also next example)
        recycleViewWordPress.setNestedScrollingEnabled(false);
        queue = Volley.newRequestQueue(this);
        swipeRefreshLayout.setRefreshing(true);
        CallingPage();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                CallingPage();
            }
        });
    }

    public void SnackBarMessage(String message) {
        Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
    }

    public void CallingPage(){
        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.HOST_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        typeForPosts =new ArrayList<WordPressType>();

                        mAdapter = new AdapterForWordPress(WordPress.this,typeForPosts);
                        recycleViewWordPress.setAdapter(mAdapter);
                        try {
                            JSONArray jsonResponse = new JSONObject(response).getJSONArray(Constants.RESPONSE);
                            int i = jsonResponse.length();

                            for (int j = 0; j < i; j++) {
                                WordPressType typeHints =new WordPressType();
                                JSONObject jsonChildNode = jsonResponse.getJSONObject(j);
                                typeHints.setResponse_id(jsonChildNode.optString(Constants.RESPONSE_1.trim()).toString());
                                typeHints.setResponse_name(jsonChildNode.optString(Constants.RESPONSE_2.trim()).toString());
                                typeHints.setResponse_link(jsonChildNode.optString(Constants.RESPONSE_3.trim()).toString());
                                typeHints.setResponse_time(jsonChildNode.optString(Constants.RESPONSE_4.trim()).toString());
                                typeHints.setResponse_content(jsonChildNode.optString(Constants.RESPONSE_5.trim()).toString());
                                typeHints.setResponse_author(jsonChildNode.optString(Constants.RESPONSE_6.trim()).toString());
                                typeHints.setResponse_image(jsonChildNode.optString(Constants.RESPONSE_7.trim()).toString());
                                typeHints.setResponse_category(jsonChildNode.optString(Constants.RESPONSE_8.trim()).toString());
                                typeForPosts.add(typeHints);
                                mAdapter.notifyDataSetChanged();
                            }
                            swipeRefreshLayout.setRefreshing(false);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            //Toast.makeText(WordPress.this,"frag a"+ e.getMessage(), Toast.LENGTH_LONG).show();
                            SnackBarMessage("JSON Exception");
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toast.makeText(WordPress.this, "error 2", Toast.LENGTH_LONG).show();
                SnackBarMessage("Volley Response Error");
            }
        });
        // Add the request to the RequestQueue.
        queue.add(stringRequest);

    }
// next activity with specific link 
    public void LoadPostView(String linkToOpen){
        Intent intent =new Intent(WordPress.this,PostView.class);
        intent.putExtra("link",linkToOpen);
        startActivity(intent);
    }
}

Also user interface for parent activity.

activity_wordpress.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/coordinatorLayout"
    tools:context="com.logicchip.wordpresstoandroid.WordPress">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/swipeRefreshLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="fill_vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
            <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="fill_vertical"
                app:layout_behavior="@string/appbar_scrolling_view_behavior">
                 <android.support.v7.widget.RecyclerView
                     android:id="@+id/recycleViewWordPress"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content">
                 </android.support.v7.widget.RecyclerView>
            </android.support.v4.widget.NestedScrollView>
        </android.support.v4.widget.SwipeRefreshLayout>
</android.support.design.widget.CoordinatorLayout>

 

Reading post

So Remember the AMP mentioned above seems like we are using it now. First of all see the xml yes it contain’s a webview, then the class file PostView. In fact parameter passed from parent activity is changed like this, from “www.yourwebsite.com/post/” to “www.yourwebsite.com/post/amp/” . As a result of this operation webview loads the AMP version of your page. Because of class MyWebChromeClient inside PostView  we can play videos in webview. Similarly MyBrowser class is for handling the clicks inside the webview along with some other functions like 404, 403 error’s etc.

activity_post_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_post_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.logicchip.wordpresstoandroid.PostView">
            <WebView
                android:id="@+id/idForLink"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </WebView>
</RelativeLayout>
PostView.java
public class PostView extends AppCompatActivity {
    private WebView idForLink;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_view);
        idForLink = (WebView) findViewById(R.id.idForLink);
        idForLink.setWebViewClient(new MyBrowser());
        idForLink.setWebChromeClient(new MyWebChromeClient());
        idForLink.getSettings().setLoadsImagesAutomatically(true);
        idForLink.getSettings().setJavaScriptEnabled(true);
        idForLink.getSettings().setAppCacheEnabled(true);
        idForLink.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        String linkToOpen=getIntent().getStringExtra("link");
        idForLink.loadUrl(linkToOpen+"amp/");
    }
    public class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            // TODO Auto-generated method stub
            super.onShowCustomView(view, callback);
            if (view instanceof FrameLayout) {
                FrameLayout frame = (FrameLayout) view;
                if (frame.getFocusedChild() instanceof VideoView) {
                    VideoView video = (VideoView) frame.getFocusedChild();
                    frame.removeView(video);
                    video.start();
                }
            }
        }
    }
    private class MyBrowser extends WebViewClient {   }
}

Constants.java

In order to keep constant values for easy access.

public class Constants {
    public static String HOST_URL="http://yourwebsite.com/yourfolder/webservice.php";
    public static String AMP="amp/";
    public static String TEMPLATE_FOR_TIME = "yyyy-MM-dd";
    public static String RESPONSE = "for_post";
    public static String RESPONSE_1 = "id";
    public static String RESPONSE_2 = "name";
    public static String RESPONSE_3 = "link";
    public static String RESPONSE_4 = "time";
    public static String RESPONSE_5 = "content";
    public static String RESPONSE_6 = "author";
    public static String RESPONSE_7 = "image";
    public static String RESPONSE_8 = "category";
}

 

 

Developing a Music Streaming Android App

For creating a audio streaming in android you must be aware of some things. Mainly database,web service,json array,php things like that. This project can be tricky. However Wamp is used as the server for php and database. Advantage of using php is it’s very easy to setup and test. Android support streaming defaultly. Only need to set type AudioManager.STREAM_MUSIC in MediaPlayer object.


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

Here a tablayout is used for category selection. Here we use 6 tabs Blues, Electronics, Folk, Hip Hop, Jazz, Pop and Rock. For database connection we use web services the server side code is in php. Only one fragment is used for all the 6 tabs, changing content according to the tab. Inorder to use web services we need a network library called volley, Add this dependencies in the build.gradle(Module:app) file


dependencies {
compile 'com.android.volley:volley:1.0.0'
}




Also add internet permission in Androidmanifest.xml.

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

 

1. Creating Database

Download wamp or xamp server and install it. Create a database called song in it a table called audio.

Now create a folder called song in the www directory of wamp or xamp whatever you are installed. Another folder called songs inside song to store your music files in there. Example a.mp3, b.mp4 etc. Add those names to the database also.

If wamp or xamp don’t run properly check Internet Information Service(IIS) Manager in windows. Also check privileges.

 

2. Php files for web service

Need two php files like.php and song.php. The song.php file is for finding and viewing songs. The like.php file is for rating the audio file.

song.php

<?php
$host="localhost"; // Host name
$servername = "localhost";
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="song"; // Database name

$conn = new mysqli($servername, $username, $password,$db_name);
$tname=$_POST['tag'];

// Check connection
if ($conn->connect_error) {
    	die("Connection failed: " . $conn->connect_error);
} else{
//echo "Connected successfully "."<br />\r\n";
}
	$jsonData      = array();
	$jsonTempData  = array();
$sql = "SELECT * FROM `audio` WHERE TYPE='$tname'";//" ORDER BY index DESC";
	$result = $conn->query($sql);

if ($result->num_rows > 0) {
while(($rowb = $result->fetch_assoc())) {
			$jTempData  = array();
      		$jTempData['id']         	=$rowb["NO"];
			$jTempData['name']         	=$rowb["NAME"];
      		$jTempData['score']         =$rowb["SCORE"];
      		$jTempData['rate']         	=$rowb["RATING"];
			$jsonData[]=$jTempData;
	}
	}else {
			$jTempData  = array();
    			$jTempData['id']         	="no";
			$jTempData['song']         	="noooo";
      		$jTempData['song']         	="noo";
      		$jTempData['song']         	="no";
			$jsonData[]=$jTempData;
}
$conn->close();

$outputArr['song'] = $jsonData;
// Encode Array To JSON Data
print_r( json_encode($outputArr));
?>

For song.php we must provide a tag. Tag for the category of songs to be selected and displayed.




like.php

<?php
$servername = "localhost";// Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="song"; // Database name

$conn = new mysqli($servername, $username, $password,$db_name);
$id=$_POST['id'];
$val=$_POST['like'];

// Check connection
if ($conn->connect_error) {
    		die("Connection failed: " . $conn->connect_error);
} else{
//echo "Connected successfully "."<br />\r\n";
}
	$jsonData      = array();
	$jsonTempData  = array();
  	$sql = "UPDATE audio SET SCORE=SCORE+'$val' WHERE NO='$id'";
	$result = $conn->query($sql);
  	$jTempData['song']         	=$result;
  	$jsonData[]=$jTempData;
  	$conn->close();

  	$outputArr['song'] =$jsonData;
  // Encode Array To JSON Data
  	print_r( json_encode($outputArr));
  ?>

For like.php we must provide id and value of rating. Updated rating can be positive or negative.

 

3. Android part

Class files for android part are MainActivity.java, Constants.java and Common.java. MainActivity holds the fragments and tabs. Also it’s where the streaming take place. Constants.java for holding the constants. Common.java for fragment class and a page adapter class for the tabs.

Comn.java

Class file comn.java contains clicks for streaming audio. Load streaming audio list and display  it.

public class Comn extends Fragment {
    int sect;
    public ListView listView;
    public static ArrayList<String> id = null, song = null, score = null, rate = null;
    public SongAdapter songAdapter;
    public RequestQueue requestQueue;

    public Comn() {

    }

    public Comn newInstance(int sectionNumber, MediaPlayer mediaPlayer) {

        Comn fragment = new Comn();
        Bundle args = new Bundle();
        args.putInt(Constants.KEY_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        requestQueue = ((MainActivity) getActivity()).getRequestQueue();
        requestQueue.getCache().clear();
        View rootView = inflater.inflate(R.layout.fragment_comn, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.t1);
        listView = (ListView) rootView.findViewById(R.id.listview_song);
        listOfSong();
        //((MainActivity)getActivity()).Snack("Json pling");
        textView.setText(getString(R.string.section_format, getArguments().getInt(Constants.KEY_NUMBER)));
        return rootView;
    }


    public void listOfSong() {

        StringRequest menuRequest = new StringRequest(Request.Method.POST, Constants.LINK,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonResponse = new JSONObject(response).getJSONArray(Constants.KEY);
                            int i = jsonResponse.length();

                            id = new ArrayList<String>();
                            song = new ArrayList<String>();
                            score = new ArrayList<String>();
                            rate = new ArrayList<String>();

                            for (int j = 0; j < i; j++) {
                                JSONObject jsonChildNode = jsonResponse.getJSONObject(j);

                                id.add(jsonChildNode.optString(Constants.TAG_ID).toString());
                                song.add(jsonChildNode.optString(Constants.TAG_NAME).toString());
                                score.add(jsonChildNode.optString(Constants.TAG_SCORE).toString());
                                rate.add(jsonChildNode.optString(Constants.TAG_RATE).toString());

                            }
                            songAdapter = new SongAdapter(getActivity(), id, song, score, rate);
                            listView.setAdapter(songAdapter);


                        } catch (JSONException e) {
                            e.printStackTrace();
                            ((MainActivity) getActivity()).Snack("Json " + e.getMessage());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        ((MainActivity) getActivity()).Snack("Volley " + error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                // the POST parameters:
                params.put(Constants.C_TAG, getResources().obtainTypedArray(R.array.type).getText(getArguments().getInt(Constants.KEY_NUMBER)).toString());
                return params;
            }
        };
        //requestQueue.getCache().clear();
        requestQueue.add(menuRequest);
    }


    public class SongAdapter extends BaseAdapter {
        Activity activity;
        ArrayList<String> id, name, score, rate;


        public SongAdapter(Activity activity, ArrayList<String> id, ArrayList<String> name, ArrayList<String> score, ArrayList<String> rate) {
            this.activity = activity;
            this.id = id;
            this.name = name;
            this.score = score;
            this.rate = rate;
        }

        public class ViewHolder {
            public TextView song_name, song_rating;
            public ImageView rate_l, rate_d, rate_p;
        }


        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.song_layout, null);
                holder = new ViewHolder();
                holder.song_name = (TextView) convertView.findViewById(R.id.song_name);
                holder.song_rating = (TextView) convertView.findViewById(R.id.song_rating);
                holder.rate_l = (ImageView) convertView.findViewById(R.id.rate_l);
                holder.rate_d = (ImageView) convertView.findViewById(R.id.rate_d);
                holder.rate_p = (ImageView) convertView.findViewById(R.id.rate_p);

                holder.song_name.setText(name.get(position));
                holder.song_rating.setText(score.get(position));

                holder.rate_p.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((MainActivity) activity).playSong(name.get(position));
                    }
                });
                holder.rate_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((MainActivity) activity).like(id.get(position), "1");
                        listOfSong();
                    }
                });

                holder.rate_d.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        ((MainActivity) activity).like(id.get(position), "-1");
                        listOfSong();
                    }
                });

                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
                holder.song_name.setText(name.get(position));
                holder.song_rating.setText(score.get(position));

            }

            return convertView;
        }
    }
}

Adapter for viewing songs is inside the comn.java class, It uses an xml file for Ui.

song_layout.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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text.mp3"
        android:id="@+id/song_name" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="right">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:layout_gravity="center_vertical"
            android:text="123456"
            android:id="@+id/song_rating" />
        <View
            android:layout_width="24dp"
            android:layout_height="24dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_play"
            android:tint="@color/black"
            android:id="@+id/rate_p"
            android:layout_gravity="center_vertical"/>
        <View
            android:layout_width="24dp"
            android:layout_height="24dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_like"
            android:tint="@color/green_500"
            android:id="@+id/rate_l"
            android:layout_gravity="center_vertical"/>
        <View
            android:layout_width="24dp"
            android:layout_height="24dp"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_dislike"
            android:tint="@color/red_500"
            android:id="@+id/rate_d"
            android:layout_gravity="center_vertical"/>
    </LinearLayout>


</LinearLayout>

fragment_comn.xml

<FrameLayout 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"
    tools:context="logicchip.cheriyidam.songstream.Comn">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/t1"
        android:visibility="gone"
        android:text="common" />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listview_song">

    </ListView>

</FrameLayout>

MainActivity.java which contains methods for streaming

public class MainActivity extends AppCompatActivity {


    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    public MediaPlayer mediaPlayer;
    public String songString="";
    public boolean intialStage = true,playPause;
    public CoordinatorLayout coordinatorLayout;
    TextView sng_name,sng_dur;
    public int dur;
    public RequestQueue requestQueue;
    public ImageView img;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        requestQueue= Volley.newRequestQueue(MainActivity.this);
        requestQueue.getCache().clear();
        mViewPager = (ViewPager) findViewById(R.id.container);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        coordinatorLayout=(CoordinatorLayout)findViewById(R.id.main_content);
        sng_name=(TextView)findViewById(R.id.sng_name);
        sng_dur=(TextView)findViewById(R.id.sng_dur);
        img=(ImageView)findViewById(R.id.icon_img);
        img.setEnabled(false);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        tabLayout.addTab(tabLayout.newTab().setText("Blues"));
        tabLayout.addTab(tabLayout.newTab().setText("Electronic"));
        tabLayout.addTab(tabLayout.newTab().setText("Folk"));
        tabLayout.addTab(tabLayout.newTab().setText("Hip hop"));
        tabLayout.addTab(tabLayout.newTab().setText("Jazz"));
        tabLayout.addTab(tabLayout.newTab().setText("Pop"));
        tabLayout.addTab(tabLayout.newTab().setText("Rock"));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount(),mediaPlayer);
        mViewPager.setAdapter(mSectionsPagerAdapter);
       // tabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer.isPlaying()){
                    playPause=true;
                    mediaPlayer.pause();
                    img.setImageResource(R.drawable.play);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }else if(playPause){
                    mediaPlayer.start();
                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                    playPause=false;
                }
            }
        });
    }
    public RequestQueue getRequestQueue(){
        return requestQueue;
    }

    public void like(final String id, final String like){
        StringRequest menuRequest = new StringRequest(Request.Method.POST, Constants.LIKE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonResponse = new JSONObject(response).getJSONArray(Constants.KEY);
                            int i=jsonResponse.length();


                            for(int j=0;j<i;j++){
                                JSONObject jsonChildNode = jsonResponse.getJSONObject(j);
                                Snack(jsonChildNode.optString(Constants.TAG_SONG).toString());

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Snack("Json "+e.getMessage());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        Snack("Volley "+error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:
                params.put(Constants.TAG_ID,id);
                params.put(Constants.TAG_LIKE,like);
                return params;
            }
        };
        //requestQueue.getCache().clear();
        requestQueue.add(menuRequest);
    }


    public MediaPlayer getMediaPlayer(){
        return mediaPlayer;
    }

    public void list(){
    }

    public void playSong(String song) {
        sng_name.setText(song);
        img.setEnabled(true);
        String songPath=Constants.SONG_LINK+song;

        //    Snack(songPath);
       try {

            if(mediaPlayer.isPlaying()){
                if(songString.equals(songPath)){
                    mediaPlayer.pause();
                    playPause=true;
                    img.setImageResource(R.drawable.play);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }else{
                    playPause=false;
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(songPath);
                    songString=songPath;
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                    //setting duration change it...
                    sng_dur.setText(String.valueOf(mediaPlayer.getDuration()));

                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }
            }else if(playPause){
                if(songString.equals(songPath)){
                    mediaPlayer.start();
                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                    playPause=false;
                }else{
                    playPause=false;
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(songPath);
                    songString=songPath;
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                    //setting duration change it...
                    sng_dur.setText(String.valueOf(mediaPlayer.getDuration()));

                    img.setImageResource(R.drawable.pause);
                    img.setColorFilter(getResources().getColor(R.color.black));
                }

            }else {
                mediaPlayer.reset();
                playPause=false;
                mediaPlayer.setDataSource(songPath);
                songString=songPath;
                mediaPlayer.prepare();
                mediaPlayer.start();
                sng_dur.setText(String.valueOf(mediaPlayer.getDuration()));
                img.setImageResource(R.drawable.pause);
                img.setColorFilter(getResources().getColor(R.color.black));
               // dur=mediaPlayer.getDuration();
                //Snack(String.valueOf(dur));
            }


            // Setup listener so next song starts automatically
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                public void onCompletion(MediaPlayer arg0) {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }

            });

        } catch (IOException e) {
            Log.v(getString(R.string.app_name), e.getMessage());
        }
    }

    public void check(){

    }


    public  void Snack(String message) {
        Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    
  

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="logicchip.cheriyidam.songstream.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:layout_scrollFlags="scroll|enterAlways">

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="30dp" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="end|bottom">
        <ImageView
            android:layout_margin="@dimen/appbar_padding_top"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/icon_img"
            android:layout_gravity="center_vertical"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/green_500"
            android:layout_margin="@dimen/appbar_padding_top"
            android:layout_gravity="center_vertical"
            android:id="@+id/sng_name"/>
        <View
            android:layout_width="60dp"
            android:layout_height="2dp"
            android:layout_gravity="center_vertical"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/red_500"
            android:layout_margin="@dimen/appbar_padding_top"
            android:layout_gravity="center_vertical"
            android:id="@+id/sng_dur"/>
    </LinearLayout>


</android.support.design.widget.CoordinatorLayout>

Constants.java

public class Constants {
    public static final String KEY_NUMBER = "key_number";
    public final static String IP="http://192.168.201.1";
    public final static String LINK="http://192.168.201.2/song/song.php";
    public final static String LIKE="http://192.168.201.2/song/like.php";
    public final static String SONG_LINK="http://192.168.201.2/song/songs/";
    public final static String KEY="song";

    public final static String TAG_ID="id";
    public final static String TAG_LIKE="like";
    public final static String TAG_NAME="name";
    public final static String TAG_SCORE="score";
    public final static String TAG_RATE="rate";
    public final static String TAG_SONG="song";

    public final static String C_TAG="tag";
}

You should replace the ip address with your wamp server running systems ip. Streaming requires ip or link for working. While using a local system ip is our best option. Don’t use “localhost” us ip. Streaming works by loading a link and retrieving it’s content. By using a localhost android try to access it which is not possible, because it’s not have any servers running. Wamp is the server running so we need to use the ip of the system. In case it’s hosted online server. We can use links like “www.yourwebsite.com/songlink.mp3” .

SectionsPagerAdapter.java

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    public MediaPlayer mediaPlayer;
    int mNumOfTabs;

    public SectionsPagerAdapter(FragmentManager fm,int NumOfTabs,MediaPlayer mediaPlayer) {
        super(fm);
        this.mediaPlayer=mediaPlayer;
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {
        Comn comn=new Comn();
        return comn.newInstance(position,mediaPlayer);

    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="red_500">#F44336</color>
    <color name="green_500">#4CAF50</color>
    <color name="white">#FFF</color>
    <color name="black">#000</color>
</resources>

icon_dislike.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>

icon_like.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>

icon_none.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M22,9.24l-7.19,-0.62L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21 12,17.27 18.18,21l-1.63,-7.03L22,9.24zM12,15.4l-3.76,2.27 1,-4.28 -3.32,-2.88 4.38,-0.38L12,6.1l1.71,4.04 4.38,0.38 -3.32,2.88 1,4.28L12,15.4z"/>
</vector>

icon_play.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M8,5v14l11,-7z"/>
</vector>

pause.xml

Pause button used for pause streaming audio.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="50dp"
        android:height="50dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z"/>
</vector>

 

play.xml

Play button used for start streaming.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="50dp"
        android:height="50dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M8,5v14l11,-7z"/>
</vector>