Introduction
Most of the Android applications use an API to send and receive data from server to client. API is very useful when applications need to send or receive data.
In this tutorial I will show you how to create a Restful JSON based API for Android application using ASP.NET and Microsoft SQL Server database.
Overview of the tutorial
This tutorial shows you the basic implementation of the RESTful API and will let you know ow to create a Restful API in Visual Studio with ASP.NET using C#.
How to connect android application with SQL Server Database
In this tutorial I am using Visual Studio 2015 (you can use any version) and Android 1.5.1 version with minimum SDK API 18: Android 2.2 (Froyo).
First we create an API
Step I:
Download required resources:
Download three JSON service DLL files from the link....
Step II:
Open Visual Studio and create ASP.NET Empty Web Application project.
For this:
Go to File, then New. Click Project. From new project window select web category. Then select ASP.NET Empty Web Application and give it a name. Select project location from Browse. Make sure Create Directory for Solution is checked. Click Ok.
Now add DLL files in the .Net web application.
- Right click on the project in Solution Explorer
- Form the menu, click on Add Reference to open the Reference Manager
- Click on Browse from left panel
- Then click browse button at bottom of Reference Manager
- Go to location where save the download files
- Select three .dll files(which you have is download) and click on add button
- Click ok
Now you need to add a handler class. For this,
- Go to project menu then click Add New Item.
- From Add New Item, select web category from left panel.
- From center select Generic Handler.
- Give it a name or left it default and click on Add button.
Now create three new classes. To add class:
- Go to project menu and click on Add New Item.
- From the code category select class.
- Give class name as SAPI.cs.
- Click Add button.
In the same way add two more classes named ISAPI and DBConnect.
Step III:
SQL Server Database Creation
Open SQL Server Management Studio and connect with server.
Create a database:
- Right click on Database folder in Object Explorer and select new database.
- Give database a name (I have given serverdb) and click OK.
Now create tables. To create table:
- Click on created database and click on New Query.
- SQLQuery window will open.
- Now execute the following SQL Query to create table,
Sql query to create table
- CREATE TABLE UserData (
- Name VARCHAR(50),
- userName VARCHAR(50),
- password VARCHAR(50),
- PhoneNumber VARCHAR(50),
- CNIC VARCHAR(50),
Step IV:
Make API and Connect Database with this and go back to visual studio.
Now we programmatically save information in database. To configure a connection open web.config file in Solution Explorer. Add the following line between <configuratio> and </configuration> tag
- <connectionStrings>
- <add name="ConString" connectionString="Data Source=DESKTOP-AU9BNOB;Initial Catalog=serverProjectdb;Integrated Security=True" providerName="System.Data.SqlCliesnt" />
- </connectionStrings>
In these lines change data source value to your Server Name. In the initial catalog change the database name with yours.
Now open DBConnect.cs class. Copy the following code into it and change the namespace with your project name.
- using System.Configuration;
- using System.Data.SqlClient;
-
- namespace TestProjectAPI
- {
-
- public class DBConnect
- {
- private static SqlConnection NewCon;
- private static stringconStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- public static SqlConnection getConnection()
- {
- NewCon = new SqlConnection(conStr);
- return NewCon;
- }
- public DBConnect()
- {
-
- }
- }
- }
Step V:
Configuring the API
To configure API interface open Handler.ashx file and copy the following code into it. Use correct namespace in your code.
- using JsonServices;
- using JsonServices.Web;
-
- namespace TestProjectAPI
- {
- public classHandler1: JsonHandler
- {
- public Handler1()
- {
- this.service.Name = " TestProjectAPI ";
- this.service.Description = "JSON API for android appliation";
- InterfaceConfiguration IConfig = new InterfaceConfiguration("RestAPI", typeof(ISAPI), typeof(SAPI));
- this.service.Interfaces.Add(IConfig);
- }
- }
- }
Now we need to change ISAPI.cs class to an interface class. To do this open ISAPI.cs and the class keyword to interface. And extend the SAPI.cs class with this Interface ISAPI.cs.
Here's the code to modify both classes.
ISAPI.cs
-
- namespace TestProjectAPI
- {
- public interface ISAPI
- {
-
- }
- }
SAPI.cs
- namespace TestProjectAPI
- {
- public interface SAPI: ISAPI
- {
-
- }
- }
Now open ISAPI.cs and copy the following code. You can change methods according to your requirements.
- using System.Data;
-
- namespace TestProjectAPI
- {
-
- public interface ISAPI
- {
- void CreateNewAccount(string Name, string userName, string password, string PhoneNumber, string CNIC);
- }
- }
Now open SAPI.cs and add the following code.
- using System;
- using System.Data;
- using System.Data.SqlClient;
-
- namespace TestProjectAPI
- {
- public classSAPI: ISAPI
-
- {
- SqlConnection dbConnection;
- public ServiceAPI()
- {
- dbConnection = DBConnect.getConnection();
- }
- public void CreateNewAccount(string Name, string userName, string password, string PhoneNumber, string CNIC) {
- if (dbConnection.State.ToString() == "Closed") {
- dbConnection.Open();
- }
-
- string query = "INSERT INTO UserDetails VALUES ('" + Name + "','" + userName + "','" + password + "','" + PhoneNumber + "','" + CNIC + "');";
-
- SqlCommand command = new SqlCommand(query, dbConnection);
- command.ExecuteNonQuery();
-
- dbConnection.Close();
- }
- }
Now we have successful code API.
Step VI:
Now run the API in your browser. At first the page gives you the error.
To solve this problem, simply add “
/Handler1.ashx” to the end of URL. In my case complete URL is “
localhost:49702/Handler.ashx”. If you use another name of Handler class then add that name instead of Handler1.ashx.
After adding this, if you see below type of screen it means your API is working.
Now at the end of URL add “?ANDROID” and complete URL becomes “
localhost:49702/Handler.ashx?ANDROID”.
Press enter and it will prompt you to save a zipped file.
Now extract that zip file and start coding with Android Studio.
Step I:
Creating Android project.
Name the project Navigation
Only one activity which is Main Activity.
Step II:
Open extracted file, then copy and paste the RestAPI.java file into your project. Change the package value with your package name.
Step 3:
Add the following permission into AndroidMenifest.xml
<uses-permissionandroid:name="android.permission.INTERNET"/>
Step 4:
Open the activity_main.xml file and add the following code into it.
Step 5 Add two more classes named
UserDetailsTable.java and JSONParser.java.
UserDetailsTable.java class map database objects to java objects.
JSONParser.java class used to parse JSONObjects
Step 6
Now open UserDetailsTable.java and add the following code into it.
- package com.example.zubariaashraf.navigation;
-
- import android.content.Intent;
-
-
-
-
- public class UserDetailsTable
- {
- String Name, userName, password, PhoneNumber, CNIC;
- int id;
-
- public UserDetailsTable(String Name, String userName,
- String password, String PhoneNumber, String CNIC)
- {
- super();
- this.id = id;
- this.Name = Name;
- this.userName = userName;
- this.password = password;
- this.PhoneNumber = PhoneNumber;
- this.CNIC = CNIC;
- }
-
- public UserDetailsTable()
- {
- super();
- this.id = 0;
- this.Name = null;
- this.userName = null;
- this.password = null;
- this.PhoneNumber = null;
- this.CNIC = null;
-
-
- }
-
- public int getId()
- {
- return id;
- }
- public void setId(int id)
- {
- this.id = id;
- }
-
- public String getName()
- {
- return Name;
- }
-
- public void setName(String Name)
- {
- this.Name = Name;
- }
-
- public String getUserName()
- {
- return userName;
- }
-
- public void setUserName(String userName)
- {
- this.userName = userName;
- }
-
- public String getPassword()
- {
- return password;
- }
-
- public void setPassword(String password)
- {
- this.password = password;
- }
-
- public String getPhoneNumber()
- {
- return PhoneNumber;
- }
-
- public void setPhoneNumber(String PhoneNumber)
- {
- this.PhoneNumber = PhoneNumber;
- }
-
- public String getCNIC()
- {
- return CNIC;
- }
-
- public void setCNIC(String CNIC)
- {
- this.CNIC = CNIC;
- }
-
- }
Now open JSONParser.java and add the following code into it. You can modify this class according to your requirements.
- package com.example.zubariaashraf.navigation;
-
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
-
- import android.annotation.SuppressLint;
- import android.util.Log;
-
-
-
-
- public class JSONParser
- {
-
- public JSONParser()
- {
- super();
- }
- }
Now open Main Activity.java and add the following code into it.
- package com.example.zubariaashraf.navigation;
-
- import android.content.Context;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.app.Activity;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.support.v4.app.NavUtils;
- import android.annotation.TargetApi;
- import android.content.Intent;
- import android.os.Build;
- import android.widget.TextView;
- import android.widget.Toast;
-
- import org.json.JSONObject;
-
- import java.sql.SQLException;
-
- public class CreateUserActivity extends Activity
- {
-
- EditText etName, etUsername, etPassword, rPassword, pNumber, uCnic;
- Button btnCreateUser;
- Context context;
- boolean value;
- String username;
-
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_create_user);
- context = this;
- Show the Up button in the action bar.
- setupActionBar();
-
- etName = (EditText) findViewById(R.id.name);
- etUsername = (EditText) findViewById(R.id.uname);
- etPassword = (EditText) findViewById(R.id.upassword);
- rPassword = (EditText) findViewById(R.id.uRepassword);
- pNumber = (EditText) findViewById(R.id.phonenum);
- uCnic = (EditText) findViewById(R.id.cnic);
-
-
- btnCreateUser = (Button) findViewById(R.id.btn_createuser);
-
-
- btnCreateUser.setOnClickListener(
- new View.OnClickListener()
- {
-
- @Override
- public void onClick(View v)
- {
-
- String firstname, password, rePassword, Pnumber, ucnic;
- firstname = etName.getText().toString();
- username = etUsername.getText().toString();
- password = etPassword.getText().toString();
- rePassword = rPassword.getText().toString();
- Pnumber = pNumber.getText().toString();
- ucnic = uCnic.getText().toString();
-
- UserDetailsTable userDetail = new UserDetailsTable(firstname, username, password, Pnumber, ucnic);
- new AsyncCreateUser().execute(userDetail);
-
- }
- });
- }
-
-
-
- protected class AsyncCreateUser extends
- AsyncTask < UserDetailsTable, Void, Void >
- {
-
- @Override
- protected Void doInBackground(UserDetailsTable...params)
- {
-
- RestAPI api = new RestAPI();
- try
- {
-
- api.CreateNewAccount(params[0].getName(),
- params[0].getUserName(),
- params[0].getPassword(),
- params[0].getPhoneNumber(),
- params[0].getCNIC());
-
- } catch (Exception e)
- {
-
- Log.d("AsyncCreateUser", e.getMessage());
-
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(Void result)
- {
- store(username);
- Intent i = new Intent(CreateUserActivity.this, LoginActivity.class);
- startActivity(i);
- }
-
- }
-
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item)
- {
- switch (item.getItemId())
- {
- case android.R.id.home:
-
- NavUtils.navigateUpFromSameTask(this);
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
-
- }
Step 7
Now run the application
To run this, the application should know the correct URL of the API. So to add this open the RestAPI class and here you will see an attribute called urlString with "
http://DESKTOP-AU9BNOB/Handler1.ashx" URL as in my RestAPI.
So to run this application on emulator you need to host your API on local server. But if you want to run application on real android device then you have to host API in public hosting site.
Run the application and enjoy.
After hosting API on local or public hosting server change the URL from the RestAPI.
Read more articles on Android: