Monday 4 March 2019

Android: Connecting to Webserver for simple data

Dear Readers,

When we are working with app development, most of the time we require accessing the particular website for the data. The website may be generally ours or some other website that provides information like weather forecast sites etc.

Traditionally data from the site could be accessed using HTML page, and whenever new data is required we were required to reload the page or load all HTML file. This works fine for static data and when the site is not required to be dynamic. However, today websites needn't need to reload the page for loading extra content, for example, facebook, twitter, youtube and soon. Thanks to the work of many developers that provided us techniques to just get the content required in the existing webpage.
Many developers like to call this as API. API may sound big enough and fancy but it just means application program interface. It is not a programming language instead it is the technique by which we can load the data in the existing webpage without reloading page.

To, my readers who have come to read this post, I assume that you have some experience in web development. If not, don't worry, I will guide you on how to get the web development knowledge required for implementing API in android. Again, Don't get overwhelmed by name API, its just nothing then a technique for accessing content in the web so that we can update the page without reloading it.

Now, let us start on the topic:

FOR THOSE FAMILIAR WITH WEBSERVER:
--
Developers at android have been helpful enough to provide the library:
https://developer.android.com/training/volley
If you like to explore more by yourself please feel free to jump in the site to get started.
But, if you would like to go with me, Feel free to join me in remaining text,

Volley library is the library distributed by the developer at android.com.It is also available in GitHub. It is made with the intention to make the call to our web server easily to retrieve the data from the web server.

First, we need to add the library to our android module: app gradle file add:
compile 'com.android.volley:volley:1.1.1' inside dependencies and it should look like below.
dependencies {
    ...
    compile 'com.android.volley:volley:1.1.1'
}

Congratulation, you have added the volley library, now the thing will get easier,

Secondly, go to the activity or class from where you will be requesting the data to the server:

Oh yes, since you are working with the internet, don't forget to add the permission for internet in your manifest file as
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

It should be kept after the end of <application/> tag and it may look like this:
     </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

Now, you are all set to resume the work,
On the activity:
//RequestQueue is the class that represents the medium to queue many requests to the web server.
here I am validating users after they press login, so I have named validate_user for RequestQueue.

RequestQueue myRequestQueue = Volley.newRequestQueue(context);
String extraString="";
// IF the webserver accept the data by post request then extraString is not required.
String url="your_website_name.com/login.php";

//IF the webserver used the GET request to receive data 
//then,extraString="?varaible1=value1&variable2=value2";
//in my case for user authentication variable1 is user and variable2 is pass
extraString="?user=value1&pass=value2";
url=url+extraString;
Now, as we have formated the desired url in the format that our webbrowser accepts; we can now request the server for the data;
Thirdly, you have to set up the response listener which stores the values retured by the webserver; Also the error listener that executes when error occurs while connnecting to server So,
//Response listener
Response.Listener listener=new Response.Listener<String>() { //Please note <String> is used
    @Override    public void onResponse(String response) { //Note: Instead 
//of Object String is used..
        Toast.makeText(context, "Congrats!! Connected Successfully to Server ", Toast.LENGTH_SHORT).show();
        Toast.makeText(context, response, Toast.LENGTH_SHORT).show(); 
//the response is the string data retured by server..
   // it may be normal echo "random strings"; by php code..
    }
};

//the error is returned in the object <VolleyError> object so notice how the object 
//is being used below
Response.ErrorListener errorListener=new Response.ErrorListener() {
    @Override    public void onErrorResponse(VolleyError error) {
        Toast.makeText(context, "Connection failed to Server ", Toast.LENGTH_SHORT).show();
        Toast.makeText(context,error.getMessage(), Toast.LENGTH_SHORT).show();
    }
};
//Since we are requesting the server for the string data: we use the class StringRequest
// used by Volley Library

StringRequest user_auth=new StringRequest(Request.Method.POST,url,listener,errorListener){
    //Since we have used the method POST to push the data to the server so, The variables 
//and values are kept in
   //MAP... As variable1 is user and Variable2 is pass
    @Override    protected Map<String, String> getParams() throws AuthFailureError {
       Map<String, String>  params = new HashMap<String, String>();
       params.put("user", username);//username is a String that I obtained from user input
       params.put("pass", password);//password is a String that I obtained from user input
       return params;
} };
myRequestQueue.add(user_auth);
You should now be able to get data from your webserver if it is configured properly
demo : login.php
<?php
 echo "Hi, I am the text sent from the php file in the webserver. I am the String and I can send other data as well in JSON and XML format";
?>
save the file as .php and keep in the same directry as index.html.. 
Be sure that you can run the php server in your system.. If you would like to know more
Search install apache and php server in windows or linux... and there are quite good video to guide you setting up the server. 
For you convinience practing this code: index.html
<HTML> <HEAD> <title>User Authentication</title> </HEAD> <BODY> <BODY STYLE="bgcolor: green; color: green;"</> <CENTER> <P> Please enter your login Crenditials. </P> <FORM action="login.php" method="post"> <TABLE> <tr><td>Username:</td><td><input type="text" name="user" value=""></td></tr> <tr><td>Password:</td><td><input type="password" name="pass" value=""></td></tr> </TABLE> <input type= "submit" value="Login"> </FORM> <CENTER> </BODY> </HTML>
I think this post was helpful for you, If you have any questions or doubts or any suggestion please comment below.
FOR THOSE NOT FAMILIAR WITH WEBSERVER:
I suggest you to search installing the apache and php in the system. After that, knowledge of HTML and basic PHP is requred to follow the post, To make more easier the HTML and Basic PHP file required for following the post is included in the post above. 
https://www.znetlive.com/blog/how-to-install-apache-php-and-mysql-on-windows-10-machine/
to learn more search install Apache and PHP in the window or linux