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.
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.
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.
WordPress part.
Web-service Part.
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 .
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);
}
}
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.
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
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.
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;
}
}