Message from Author

Following tutorial is currently not up to date and there are lots of bug in it. Please don’t use this tutorial to any of your production work.

Please click below link to the new tutorial in restful api

Restful API for Android and IOS using ASP.NET Web API 2

Thank you

 

This is the Part 2 of Restful API for Android using ASP.net and SQL Server tutorial.  In this tutorial I’ll show you how to use the created restful API in an android application. If you didn’t refer Restful API for Android Part 1 please complete that tutorial before start this (Or download the sample code from part 1).

What you need from Create Restful API for Android Part 1

To continue with this tutorial I assume that you have completed the Part 1 of this tutorial. Also I assume that you have downloaded the android APIClient.zip file from server. You need to extract download API client file. Okay Let’s Start the Tutorial …

Video Tutorial Walkthrough

Step 1: Initialize the Android Project

Create a new Android project with following settings.

  • Application Name: “RestfulAPIClient
  • Project Name: RestfulAPIClient
  • Package Name: com.tutecentral.restfulapiclient
  • Minimum Required SDK: API 18: Android 2.2 (Froyo)
  • Activity Name: MainActivity
  • Layout Name: activity_main

Now open the “APIClient” folder which you have extracted. Then Copy and paste the “RestAPI.java” file into your project. Open the class and change the package value to “com.tutecentral.restfulapiclient” (use the correct package which you copied the RestAPI.java file)

Add the following permission to AndroidManifest.xml

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

Now you need to create below activities in your project.

Activity Name

Layout Name

LoginActivity activity_login
UserDetailsActivity activity_user_details.xml
CreateUserActivity activity_create_user.xml
DeptActivity activity_dept.xml

Next you need to create 3 classes list down below. 

  1. DeptTable
  2. UserDetailsTable
  3. JSONParser

Now we have created all class and activates of the application.

Step 2: Let’s Code

First you need add below xml into your “string.xml” file in “res=>values” folder

    <string name="login">Login</string>
    <string name="username">Username :</string>
    <string name="password">Password :</string>
    <string name="user_details">User Details</string>
    <string name="firstname">First Name:</string>
    <string name="lastname">Last Name:</string>
    <string name="title_activity_create_user">CreateUserActivity</string>
    <string name="create_user_account">Create User Account</string>

Now you need to change  all layout file according to below codes. It’s better to copy and paste the xml into your layout files.

<RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" >

    <ListView android:id="@+id/lv_main" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

 

<RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".LoginActivity" >

    <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="33dp" android:text="@string/login" android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_marginTop="30dp" android:layout_toLeftOf="@+id/textView1" android:text="@string/username" android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText android:id="@+id/et_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:layout_marginTop="16dp" android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText android:id="@+id/et_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_below="@+id/textView3" android:layout_marginTop="16dp" android:ems="10" android:inputType="textPassword" />

    <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView2" android:layout_below="@+id/et_username" android:layout_marginTop="20dp" android:text="@string/password" android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button android:id="@+id/btn_Login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/et_password" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:text="@string/login" />

</RelativeLayout>

 

<RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".CreateUserActivity" >

    <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="26dp" android:text="@string/create_user_account" android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:layout_marginTop="22dp" android:text="@string/lastname" android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView3" android:layout_below="@+id/textView3" android:layout_marginTop="20dp" android:text="@string/username" android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView4" android:layout_below="@+id/textView4" android:layout_marginTop="20dp" android:text="@string/password" android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="50dp" android:text="@string/firstname" android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText android:id="@+id/et_fisrtname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_alignParentRight="true" android:layout_toRightOf="@+id/textView2" android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText android:id="@+id/et_lastname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView3" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/et_fisrtname" android:layout_alignRight="@+id/et_fisrtname" android:ems="10" />

    <EditText android:id="@+id/et_cu_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView4" android:layout_alignBottom="@+id/textView4" android:layout_alignLeft="@+id/et_lastname" android:layout_alignRight="@+id/et_lastname" android:ems="10" />

    <EditText android:id="@+id/et_cu_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView5" android:layout_alignBottom="@+id/textView5" android:layout_alignLeft="@+id/et_cu_username" android:layout_alignRight="@+id/et_cu_username" android:ems="10" />

    <Button android:id="@+id/btn_createuser" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/et_cu_password" android:layout_centerHorizontal="true" android:layout_marginTop="34dp" android:text="@string/create_user_account" />

</RelativeLayout>

 

<RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".UserDetailsActivity" >

    <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="39dp" android:text="@string/user_details" android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginLeft="16dp" android:layout_marginTop="32dp" android:text="@string/firstname" android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView android:id="@+id/tv_firstname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_marginLeft="28dp" android:layout_toRightOf="@+id/textView2" android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tv_firstname" android:layout_marginTop="20dp" android:layout_toLeftOf="@+id/tv_firstname" android:text="@string/lastname" android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView android:id="@+id/tv_lastname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView3" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/tv_firstname" android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

 

<RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".DeptActivity" >

    <ListView android:id="@+id/lv_dept" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

We are done with our layout files. Next we need to update “DeptTable.java”, “UserDetailsTable.java” and “JSONParser.java” class.  “DeptTable.java” and “UserDetailsTable.java” class used to map the database objects into java objects. First open the “DeptTable.java” class. This class is used to map database department data into java object. Modify the class according to below code.

package com.tutecentral.restfulapiclient;

public class DeptTable {

	int no;
	String name;

	public DeptTable(int no, String name) {
		super();
		this.no = no;
		this.name = name;
	}

	public DeptTable() {
		super();
		this.no=0;
		this.name = null;
	}

	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

Next open the “UserDetailsTable.java” class. This class is used to map user detail data which return by database into a java object. Update the class according to below code.

package com.tutecentral.restfulapiclient;

public class UserDetailsTable {

	String firstName,lastName,userName,password;

	public UserDetailsTable(String firstName, String lastName, String userName,
			String password) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.userName = userName;
		this.password = password;
	}

	public UserDetailsTable() {
		super();
		this.firstName = null;
		this.lastName = null;
		this.userName = null;
		this.password = null;

	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	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;
	}

}

Now open the “JSONParser.java” class. This class is used to parse JSONObjects.  The API always returns JSONObject type object as respond. So we need to convert those object into some other type to use it in our application. All the methods in “JSONParser.java” class get a JSONObject type of parameter. Those methods will convert the JSONObjects into some other object type where we can use those converted object in our application directly. Below methods are used to parse methods in my API. So when you using your own API in your application write your own parsing methods. Now you update class according to below code.

package com.tutecentral.restfulapiclient;
import java.util.ArrayList;

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

import android.util.Log;

public class JSONParser {

	public JSONParser()
	{
	super();
	}

	public ArrayList<DeptTable> parseDepartment(JSONObject object)
	{
		ArrayList<DeptTable> arrayList=new ArrayList<DeptTable>();
		try {
			JSONArray jsonArray=object.getJSONArray("Value");
			JSONObject jsonObj=null;
			for(int i=0;i<jsonArray.length();i++) { jsonObj=jsonArray.getJSONObject(i); arrayList.add(new DeptTable(jsonObj.getInt("no"), jsonObj.getString("name"))); } } catch (JSONException e) { // TODO Auto-generated catch block Log.d("JSONParser => parseDepartment", e.getMessage());
		}
		return arrayList;
	}

	public boolean parseUserAuth(JSONObject object)
	{	boolean userAtuh=false;
			try {
				userAtuh= object.getBoolean("Value");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Log.d("JSONParser => parseUserAuth", e.getMessage());
			}

			return userAtuh;
	}

	public UserDetailsTable parseUserDetails(JSONObject object)
	{
		UserDetailsTable userDetail=new UserDetailsTable();

		try {
			JSONObject jsonObj=object.getJSONArray("Value").getJSONObject(0);

			userDetail.setFirstName(jsonObj.getString("firstName"));
			userDetail.setLastName(jsonObj.getString("lastName"));

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.d("JSONParser => parseUserDetails", e.getMessage());
		}

		return userDetail;

	}

}

Now we need to update the activity class. First Open the “MainActivity.java” and update it as below code.

package com.tutecentral.restfulapiclient;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

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

        String listItem []={"Login","Create User Account","Department  Details"};
        ListView lvMain=(ListView)findViewById(R.id.lv_main);
        lvMain.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItem));

        lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				if(arg2==0)
				{
					Intent i=new Intent(MainActivity.this,LoginActivity.class);
					startActivity(i);
				}
				else if(arg2==1)
				{
					Intent i=new Intent(MainActivity.this,CreateUserActivity.class);
					startActivity(i);
				}
				else if(arg2==2)
				{
					Intent i=new Intent(MainActivity.this,DeptActivity.class);
					startActivity(i);
				}
			}
		});
    }

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

}

Next you need to update “LoginActivity.java”.  Code in this class are self-explaining so I’ll not explain the code. If you didn’t understand please watch the demonstration video

package com.tutecentral.restfulapiclient;

import org.json.JSONObject;

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.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class LoginActivity extends Activity {

	EditText etUserName, etPassword;
	Button btnLogin;
	Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// Show the Up button in the action bar.
		setupActionBar();

		// Initialize  the layout components
		context=this;
		etUserName = (EditText) findViewById(R.id.et_username);
		etPassword = (EditText) findViewById(R.id.et_password);
		btnLogin = (Button) findViewById(R.id.btn_Login);

		btnLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String username=etUserName.getText().toString();
				String password=etPassword.getText().toString();

				// Execute the AsyncLogin class
				new AsyncLogin().execute(username,password);

			}
		});

	}

	protected class AsyncLogin extends AsyncTask<String, JSONObject, Boolean> {

		String userName=null;
		@Override
		protected Boolean doInBackground(String... params) {

			RestAPI api = new RestAPI();
			boolean userAuth = false;
			try {

				// Call the User Authentication Method in API
				JSONObject jsonObj = api.UserAuthentication(params[0],
						params[1]);

				//Parse the JSON Object to boolean
				JSONParser parser = new JSONParser();
				userAuth = parser.parseUserAuth(jsonObj);
				userName=params[0];
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d("AsyncLogin", e.getMessage());

			}
			return userAuth;
		}

		@Override
		protected void onPreExecute() {

			super.onPreExecute();

			Toast.makeText(context, "Please Wait...",Toast.LENGTH_SHORT).show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub

			//Check user validity
			if (result) {
				Intent i = new Intent(LoginActivity.this,
						UserDetailsActivity.class);
				i.putExtra("username",userName);
				startActivity(i);
			}
			else
			{
				Toast.makeText(context, "Not valid username/password ",Toast.LENGTH_SHORT).show();
			}

		}

	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:

			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

Next Update the “CreateUserActivity.java” class. This activity used to create users. When user is created it will redirect to LoginActivity.

package com.tutecentral.restfulapiclient;

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;

public class CreateUserActivity extends Activity {

	EditText etfirstName, etLastName, etUsername, etPassword;
	Button btnCreateUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_user);
		// Show the Up button in the action bar.
		setupActionBar();

		etfirstName =(EditText) findViewById(R.id.et_fisrtname);
		etLastName = (EditText) findViewById(R.id.et_lastname);
		etUsername = (EditText) findViewById(R.id.et_cu_username);
		etPassword = (EditText) findViewById(R.id.et_cu_password);
		btnCreateUser=(Button) findViewById(R.id.btn_createuser);

		btnCreateUser.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String firstname, lastname, username, password;

				firstname = etfirstName.getText().toString();
				lastname = etLastName.getText().toString();
				username = etUsername.getText().toString();
				password = etPassword.getText().toString();

				UserDetailsTable userDetail = new UserDetailsTable(firstname,
						lastname, username, password);

				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].getFirstName(),
						params[0].getLastName(), params[0].getUserName(),
						params[0].getPassword());

			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d("AsyncCreateUser", e.getMessage());

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			Intent i = new Intent(CreateUserActivity.this, LoginActivity.class);
			startActivity(i);
		}

	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

Next you need to update  “UserDetailsActivity.java” class. This activity will retrieve  user information from server  and display to user.

package com.tutecentral.restfulapiclient;

import org.json.JSONObject;

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.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class UserDetailsActivity extends Activity {

	TextView tvFisrtName, tvLastName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_details);
		// Show the Up button in the action bar.
		setupActionBar();

		tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
		tvLastName=(TextView)findViewById(R.id.tv_lastname);

		Intent i=getIntent();
		String username=i.getStringExtra("username");

		new AsyncUserDetails().execute(username);

	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	protected class AsyncUserDetails extends AsyncTask<String,Void,UserDetailsTable>
	{

		@Override
		protected UserDetailsTable doInBackground(String... params) {
			// TODO Auto-generated method stub
			UserDetailsTable userDetail=null;
			RestAPI api = new RestAPI();
			try {

				JSONObject jsonObj = api.GetUserDetails(params[0]);
				JSONParser parser = new JSONParser();
				userDetail = parser.parseUserDetails(jsonObj);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d("AsyncUserDetails", e.getMessage());

			}

			return userDetail;
		}

		@Override
		protected void onPostExecute(UserDetailsTable result) {
			// TODO Auto-generated method stub

			tvFisrtName.setText(result.getFirstName());
			tvLastName.setText(result.getLastName());

		}

	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

Next update “DeptActivity.java” activity class.  This class used to display department details in a simple list view.

package com.tutecentral.restfulapiclient;

import java.util.ArrayList;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class DeptActivity extends Activity {

	ArrayAdapter<String> adapter;
	ListView listv;
	Context context;
	ArrayList<String> data;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dept);
		// Show the Up button in the action bar.
		setupActionBar();
		data = new ArrayList<String>();
		listv = (ListView) findViewById(R.id.lv_dept);
		context = this;

		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, data);
		listv.setAdapter(adapter);
		Toast.makeText(this,"Loading Please Wait..",Toast.LENGTH_SHORT).show();
		new AsyncLoadDeptDetails().execute();

	}

	protected class AsyncLoadDeptDetails extends
			AsyncTask<Void, JSONObject, ArrayList<DeptTable>> {
		ArrayList<DeptTable> deptTable = null;

		@Override
		protected ArrayList<DeptTable> doInBackground(Void... params) {
			// TODO Auto-generated method stub

			RestAPI api = new RestAPI();
			try {

				JSONObject jsonObj = api.GetDepartmentDetails();

				JSONParser parser = new JSONParser();

				deptTable = parser.parseDepartment(jsonObj);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d("AsyncLoadDeptDetails", e.getMessage());

			}

			return deptTable;
		}

		@Override
		protected void onPostExecute(ArrayList<DeptTable> result) {
			// TODO Auto-generated method stub

			for (int i = 0; i < result.size(); i++) { data.add(result.get(i).getNo() + " " + result.get(i).getName()); } adapter.notifyDataSetChanged(); Toast.makeText(context,"Loading Completed",Toast.LENGTH_SHORT).show(); } } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

Now we have completed the application. But still you can’t run application without some configurations.

Step 3: Final Task to Run the Application

To use this application, application needs to access the API through the emulator or using real android device. To access the API, application needs to know the correct URL for the API. You need to provide the correct URL in “RestAPI.java” class. When you open the “RestAPI.java” class you will see an attribute called “urlString” with a value similar to this http://AHAMEDISHAK/Handler1.ashx. This is the default value for “urlString” attribute in my “RestAPI.java”. This URL cannot accessible through the emulator or in a real device.  So you need to make this URL point to the restful API.

If you host this restful API in your local host (In your PC) then you can’t access it using a real android device (In other words application will not work in a real device).   To access the restful API through a real device you need to host this restful API in a public hosting space. Then application can access it through internet publicly similar to accessing a website. I will show you how to access this API in an emulator using local host and how to access this using a real android device by hosting this in a public hosting space.

Step 3.1: Run the Application in an Android Emulator

To access localhost thought the emulator you need to provide the IP address of the emulator and port number of the Restful API with Handler1.ashx . To check  emulator can access the restful API type the below URL in emulator browser then you should get the restful API “Handler1.ashx page. If browser accesses the restful API successfully then change the “urlString” value to that URL. Then you should able to run the application without any errors.  

[quote_center]

Note : Port number may different in your case. Copy the correct API URL from browser then  use the ip address instead of localhost. 

[/quote_center]

URL for Traditional Android Emulator  

  • http://10.0.2.2:7541/Handler1.ashx
  • http://192.168.56.1:7541/Handler1.ashx

URL for Genymotion Emulator

  • http://192.168.56.1:7541/Handler1.ashx

If emulator browser unable to access the restful API from above URLs then you need to host the API in your local IIS server. Watch below video to host the API in your local IIS server.

Host the restful API in local IIS Server

Step 3.2: Run the Application in a Real Android Device

To access the restful API through a real android device you need to host the API in a public hosting space in the internet. Then you can get a public web URL to access the API. Using that URL you can access the API from real android device. Try to access the API from mobile browser using that URL. If you able to access the API through mobile browser then application also can access the API through a real android device. You can set the “urlString” value to your public web URL.  Then you can run the application to see the results.  Watch below video to host the API in a free web hosting provider.

Host the restful API in a Public Hosting Space

Step 4: What Next

Using  one of the above methods you can run the application. You create your own API according to your requirement and use it as I mention in this tutorial. If you have any issues regarding this tutorial please feel free to ask. Use comment section for communicate with me. I’ll try my best to solve your problems or you can post your question at StackOverflow to get a better solution. If you think this tutorial is valuable please share it with you friends. Subscribe for the website using your email or Subscribe to our social pages in FacebookGoogle Plus and YouTube to get instant notification about our new tutorials and videos.  Thank you very much for visiting our website. Don’t forget to check our other tutorials.

Downloads

Download the Sample Application

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

  • user123

    Hello i have use these code and getting error in android app
    I think i am not able to connect with database
    Plz tell me which url string is use in restapi.java

    • Ahamed Ishak

      IF you are running it in a android emulator you need to use http://10.0.2.2:7541/Handler1.ashx.. in url String.. (port number may different in your URL ) Or Try to host the api in your local iis server..

      Can you tell me the error.. To find the error in api.. Try below code in doInBackground() method in DeptActivity

      JSONObject jsonObj = api.GetDepartmentDetails();
      Log.d(“DeptActivity”,jsonObj.toString());

      Check the log then you will find the error there

      • user123

        Hi i have try these but still it dnt work .
        I have host the api and got the url as localhost/simmi/Handler1.ashx
        So i have taken the url as http://10.0.2.2/simmi/Handler1.ashx

        Following are the log

        • Ahamed Ishak

          according to your log there is a problem in OnPostExecute method.. It throws a NullPointerException.. It means some variables you have used in this method only declared not initialized. Please check your all global variables are initialized in onCreate().. If you still having the problem download the sample application and try to do a depth comparison between your code. By doing this you’ll find the problem in your code..

          • Nauna IMY

            Hi,

            How can i add the department filter in department activity. Like instead of showing all department i want to take the input from user and based on input i want to show the data. please guide.

          • Ahamed Ishak

            It all based on your sql query.. Make a method in your api to with correct parameters then pass those parameters to your sql query for a example Select * from department where deptID=’your parameter’ ; then call that method in your android application

          • Nauna IMY

            Hey,

            I have downloaded your code and trying to adjust it but I am stuck.

            As you suggested I have added the parameter “dept” in the sql query, compile and download the API and paste it the project.

            I have also added one edit text box(txtdept) to take the input from user and a button(btnview) in activity_dept.xml.

            Please guide me where should i edit your code to pass the text box value to parameter and on button click event bind the data.

            I will be very grateful for your facilitation in learning process.

          • Nauna IMY

            Any luck with the request

        • Haroon Amjad

          Nice Work Bro!!!
          i have a problem, when i try to download API client zip folder, instead it gives me Handler1.ashx
          Plz Solve My Problem!!!

          • Ahamed Ishak

            It cannot be ?ANDROID should give a zip file. client file will be in that zip file

          • Haroon Amjad

            i got the zip file and your program is working!!!!
            Please Tell me how to upload This database on a private web host and Then access it From Android Phone…….

          • Ahamed Ishak

            Check the tutorial I have posted a video there how to host this api in a public hosting space..

        • Brz

          did someone downloaded the APIClient.zip please send to me via mail because i couldn’t download it
          my email :
          hassanisaeed19@yahoo.com

  • hdpavan

    Hi Ahamed i need a tutorial on android twitter oauth login
    please i am in need of it for my college project , i will be coming back to your blog to read more
    thank you

    • Ahamed Ishak

      Yes I’ll definitely.. But It take time.. Can’t tell a specific date.. But probably after April 30th. Bcoz I have lot work to do in this mouth. For me It take more than 2 weeks for one tutorial… Subscribe to my website or subscribe to all social pages so you will not miss any tutorials..

      Thank you very much…

      • hdpavan

        Sir I need Atleast Oauth Login , i am trying hard since one month , i have code but i am getting http 403 error i googled a alot i dint find , it would be a great help if you try to write by this weekend , please i am in desperately need of it
        Thank you

        • Ahamed Ishak

          Sorry to tell I Don’t have time to spend on that. I have tight schedules to cover. Sorry dude…

  • Jun Baay

    Very intuitive tutorial. Thank you for sharing your knowledge. This is a big help for my current enterprise db app project… two thumbs up for you!

  • Zehra Hussayn

    Excellent tutorial Bro. Can you share how to get images from database and view in android app, if the path of images is saved in database.

    • Ahamed Ishak

      Use Below Method to load image from the URL

      URL url = new URL(“Pass the Image URL here “);
      Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
      imageView.setImageBitmap(bmp);

      • Zehra Hussayn

        Thanks Bro. I am really impressed by your instant reply. Keep it up.

  • Jun Baay

    Hi Ahamed, can you also please include a delete method in the ServiceAPI and show how to code the source say “DeleteUser.java”? Hope to see your kind response here… thanks!

    • Ahamed Ishak

      It is very easy.. You can do it by yourself. Simply create a Delete method on Service.cs then rebuild the project and download the new APIclient file. Then call that method in your android project.

  • richard

    Mr Ahamed Ishak >>>i am getting following eror if i run my real android device can you help to solve this error…….. java.net.SocketTimeoutException: failed to connect to /192.168.1.151 (port 80) after 60000ms,

    • Ahamed Ishak

      What is the urlString you mention in the RestAPI.java. It seems you have put an IP address which is not accessible through the real android device. Check that url can access the Handler1.ashx file through the mobile browser. If not you need to host api in public hosting space and provide that URL to access the API

  • richard

    http://192.168.1.151:8080/bh/Handler1.ashx this is the url am using ,this url working fine in emulator but not real device why?this ip is my system ip address

    • Ahamed Ishak

      You can’t access this URL using real device. you need to host the API in a public hosting space. Or you need to make your PC as a public host then access the API through the wifi. To do that please Google.. But it may be a tedious work. Hosting the API in a public hosting space is easy than making your own host.

      • richard

        thanks for your reply boss…

  • richard

    Mr Ahamed Ishak>>>>>>> can you show how to pass date object to rest.java file , beacuse i find difficult to send date object to rest file , i have sql server database as back end… thanks in advance

    • Ahamed Ishak

      you trying to send a java Date object?

  • kwanman9413

    How can I show the data on android device in other way?

  • Hürkan SEYHAN

    Hi Ahamed,

    We try to execute your code. But we got an error like
    failed to connect to tutecentral.somee.com/208.94.246.101 (port 80) after 60000ms

    Then emulator force to close because of null pointer exception.
    How we can solve this problem.
    Thank you for this tutorial and help.

  • Ainagul Noka

    i run the app in emulator, but when i click something (ex. departament), the app is crashed. there is a this kind of msg “05-12 06:47:14.928: E/AndroidRuntime(1499): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.tutecentral.restfulapiclient/com.tutecentral.restfulapiclient.DeptActivity}; have you declared this activity in your AndroidManifest.xml?” in a logcat. How can i fix this problem?

  • Saeed al-haidary

    Thanks Ahmed
    This is very good example work exactly
    But when I create new project and get copy your code to new project not work what you think ?
    How I can debugging code line by line?

  • Gulzar Ali Sofi

    What ip and port should i Use when i am hosting db on somee.com

    • Ahamed Ishak

      Simply use the URL of your somee.com..

      For a example : http://tutecentral.somee.com/Handler1.ashx in RestAPI.java

      • Gulzar Ali Sofi

        sorry bro I tryed it on both emulator and phone but neither user was created nor I was logged in

        • Ahamed Ishak

          Then there should be some problem with your code.. Check the video walkthrough of this tutorial . https://www.youtube.com/watch?v=7QS3PVNBEg8

          • Gulzar Ali Sofi

            Brother, I watched all the videos for Restful API and copy paste you code as shown in video but still is am facing same problem. I am not even getting an error

          • Ahamed Ishak

            Check your logcat to find the error

          • Gulzar Ali Sofi

            Thanks, Bro at last I succeed in making connection and login
            thanks thanks a lot.

          • Zineb Chams

            please i have the same problem like you had, can you tel me how did you solve ur problem

  • plus minus

    Hello Ahamed! It’s a great work!!! I am new in Android development. Can you help me with your “RestfulAPIClient” project. I have only Android 2.3.3 version. When I try to run your project I have an error with setupActionBar() function and styles.hml also. What should I do to downgrade the project to Android 2.3.3?

  • laxman kumar

    bro i have downloaded ur code and tried to run in android emulator . its running perfectly. in URLString ur somee.com url is given bt when i host same program (same steps followed as u perform in video) what i have downloaded from first tutorial and change the url with my somee.com url and tried to run the program in emulator . it doesnt work. i didnt get any error in while fetching the department details but do data appears on screen . same while registering the user it doesnt give error but when i do login with register user name and password it says invalid username password…in emulator logcat i checked its giving some kind of notification “no value of value”

  • jui shah

    hi ,

    i found yr tutorial very usefull ..but can u please tell me instead of somee.com , i have my private server and i want to host my api using that iis server so what changes i need to make in url nd all other place.. i have tried by changing my url in service.java with the address of that hosted api…like url=”http://xyz.com” but my app is not able to access data..plz helpp..ASAP..

  • guests

    Hi, Thank you for making this tutorial it has been very helpull. I do however have a problem and i was wondering if you could help me. D/JSONParser => parseDepot(2714): No value for value I keep getting this error. I dont think its your code but could it possibly be something wrong with the API…im using my own database so its called depot

    • Ahamed Ishak

      This error occurs because some logical error in your asp.net code or if you didn’t pass correct parameters to the function call. Please check your code.

  • Sourabh

    Thanks buddy… great tutorial…. was searching for this particular solution for almost 2 weeks…

  • Randy Brazeau

    Thanks for the tutorial, well done. Everything looks good except I’m not receiving any data or able to write to the SQL server 2008. I’m receiving the same error as Safa. “no Value for value”. Has anyone resolved this issue?
    Thanks
    Randy

    • Ahamed Ishak

      This error occurs because some logical error in your asp.net code or if you didn’t pass correct parameters to the function call. Please check your code

      • Safa Rashid

        I was using 2010, use 2012 and u don’t get the error

    • Randy Brazeau

      For anyone that is interested, I resolved the issue with the no value for value error message. It was not passing the correct user name. Check the Event log for SQL messages. It works great after I added a SQL user and change the connection string in the service and removed the integrated security.
      Again thanks for the tutorial.

      • dhavalgherwada

        please elaborate
        thanks in advance

      • Luca Vitrini

        Pls be more specific 🙂 What have you done to resolve it?

  • Safa Rashid

    Hi, i have a method in my api that is similar to getdept() but requires two string parameters, how would i implement this in eclipse by adding code to the deptactivity.java which im trying to modify

  • Safa Rashid

    also getting this error,

    Can’t create handler inside thread that has not called Looper.prepare()

    any help would be great!!

  • mili

    hey thnx for this tute
    heres a problem. i could not find iis manager in iis express folder.can u tell where i can be

  • Ernie Lopez

    Ahamed,

    I am curious about the JSON DLLs that you use in this tut. Are they part of an open source project. Where can i get more info?

    Thanks you for the tutorial!

  • Mar Mar

    Hello, I keep getting the following error whenever I make connection with the database.

    org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONObject

  • Kushan Dilranga Wickramasinghe

    Sir, What i need to know is , suppose i have written a webservice, lets say the one which shows the department details, and my requirement is for that interface (activity) to refresh automatically every 10s so that when the data in the hosted database changes, the list also automatically changes. How can i make that happen???

    Also, must admit that the tutorial was awesome and helped me alot.
    Thanks & Regards

    • Ahamed Ishak

      You can use a Service to check the changes in database.

  • kkp

    I have followed all the steps, I even downloaded your sample code to see how this work, i don’t have any connection with the database apparently, meaning the client app (android) is not updating the userdetail table in SQL, nor pulling the Dept data. The user name and password of user created is invalide, what could be my problem

    • Ahamed Ishak

      Try to debug your API code. Also check the Database connection string. I cant specifically tell what is the issue. Do a debug on API side so you can find out the problem

  • David Oddoye

    Any idea how i can implement this via javascript?

  • Vinay Kumar Gupta

    We got here smart and reliable knowledge

  • Sanmit Shah

    Where is the RestAPI.java file?…The folder I extracted from http://localhost:7541/HANDLER1.ASHX?Android contains service1.java..so please help..also it would be nice if you could tell me do I have to change the package name “JSONWebAPI” to com.tutecentral.restfulapiclient..a bit confuse…please help..

  • Mohd Azizan Abd Ghani

    Its works..!! thanks bro, Its good if you can share some example how to parse the file/image from android to the API using JSON object and how the API response and save the file into a dedicated directory.

    • Kelvin

      Hi, i am a bit stuck on the app… i recreated the same application using the given steps but when i run the android app it does not list the departments yet there is connection to the database. any way you can assist?

  • Kelvin

    Hi i have followed your tutorial upto the last detail but i am getting a java.lang.nullpointerexception at onPostExecute line 79… Help please

    • Ahamed Ishak

      there should be some error in your application. I cannot tell what is the problem with your program. Better debug your code

      • Kelvin

        I fixed that issue but now i am stuck with the no Value for Value error.

        • Ahamed Ishak

          There can be many reason for this. Check your SQL Query, Check the Parameters you passed when calling methods from client file.

          • Kelvin

            I found the problem… i had to create the database under the username i was going to use thus gain access to the database.. Thank you for your tutorial it has helped me alot

          • Luca Vitrini

            Can you be more specific? How did you make it work?

          • Rick Anthony G Portes

            Sir Kelvin I’m stuck with the error NO VALUE FOR VALUE, how did you solved it? In my case I can register a new user to the database but cannot login. Pls help thanks.

    • karishma

      i’m also getting the nullpointerexception at line 79. can u help me to solve the problem. thanks in advance.

      • Kelvin

        can your application login?

  • Hi, I use your tutorial in my application and it always result 0 items !!! my question is should I authenticate user first? actually I upload my ASP.Net API on the host and I just need to fetch data from it, no user need in my project! what’s wrong with it ? I should mention that I use Linq in my asp.net to fetch data and return a List ! is it the problem ???

    thanks for your answer and for your tutorial 🙂

    • Ahamed Ishak

      There should be a problem with your linq query. Better check it twice. Also you no need to authenticate user.

  • Hi, thanks for your tutorial, my jsonObject return this error : “ErrorMessage”:”Internal server error”,”Successful”:false, what is wrong with it ?! is it necessary to authenticate user to get data from the api???

    • Ahamed Ishak

      Error message it self mention the problem. There should be a problem with server. Check the server URL and DB connection

      • Şeyhmus Gümüş

        my db conneciton and server url are true but i take this “ErrorMessage”:”Internal server error”,”Successful”:false error why

    • Adam Scott

      For this error just check on your correct db mostly your connection string contains an error. The connection string must be something like this…..

  • Onur

    Hello, i have a problem with Null values at database. parser gets data until it comes to a null value. how can i solve this?

    • Onur

      ok , i’ve solved 🙂 i’ve used ISNULL with sql select query

  • Mana

    Hi, thank you for the tutorial,

    I keep getting this error while trying to get data from database the way you explained

    “Successful”: false,

    “ErrorMessage”: “Internal server error”

    }

    I’ve checked my DB connection and my URL and nothing wrong with them…
    and also I changed nothing of your code I am only trying to run it using public hosting…
    any solution please?

    • Bryan Lighton

      Make sure you are using the code reference and not he word. eg. ?ANDROID, instead of Android

  • qtq000

    Hi,

    I did every single step but something is missing here: Deploying web service for using it on Android Emulator. How can I publish the web service and deploy it on IIS?

  • Bryan Lighton

    I have used this with great results on android. Do you have any documentation examples for using the same on IOS. I am not sure how to use the resful.h and resful.m files downloaded and how to parse with json to a picker IOS.

    • Bryan Lighton

      Eventually worked through this if anyone is interested. You have to parse with NSMutableDictionary, into an NSMutableArray. All values are Mutable as they are undefined from this api. Be sure to run your method of retrieval in a detached_sync background call, similar to the async in android

    • Aatif

      hey, are you run your app with local server ? i run app with local server after publishing asp.net project but not get result on app .. means no user login , no register ..

  • Şeyhmus Gümüş

    hello everybody ı have problem when ı use my url

    http://www.gumuseyhmus.somee.com/Handler1.ashx

    ı get internal service erro successful flase what is wrong with me please help me 🙁

  • Sachin Verma

    Thanks dude this example very helpful me…………..
    Good job

  • Elias

    Thanks for the example, kindly i need help i used the example and every thing is working fine (get departments & authentication…) except creating new user, nothing happens after creating new user DB remains empty. please note that if i add new user manually to data base… I’m able to login.

  • samhitha

    too good. it helped a lot. Thank you

  • noeg chelsea

    it works n thanks, but how to put the array data in custom listview, DeptTable for example…

  • Numair Qadir

    Hi, thanks for your tutorial.. I’m having problem in connecting Android app with server.. In your example source code, there is a project “TestAndroidAPI”. I can get all my required result from it, but from Android device / Emulator / GenyMotion Emulator , it is continuously giving me error {“ErrorMessage”:”Internal server error”,”Successful”:false}. I’ve followed the steps that are in video. I’m using IIS7 , SQL Server 2012, Visual Studio 2013.

    Help needed. Thanks in advance.

  • Kirk De Veyra

    This is very helpful tutorial. But i want to ask. how do i populate data into my custom listview using this reference(Specifically the Department Details). Is there anyone could help me?

  • Aatif

    I got this error while publishing locally website … what’s the solution ?

    • Aatif

      I solve this issue .. and after successfully run app, its not working properly, not login and also not register a new user , i connect my app with local server after publishing asp.net project .. here is my final link [http://localhost:8081/] that working on browser, i set default path Handler1.ashx in IIS Server ..

      • Navax

        how did you solve the problem

        • miguel

          i solve installing the asp.net

          run %windir%Microsoft.NETFrameworkv4.0.21006aspnet_regiis.exe -i

  • Rafiqul Islam

    Assalamualikum,

    I download all
    file from your articles. I am using SQL server 2008R2 , Asp.net , framework 4,
    eclipse -JEE- LUNA, IIS, SDK 17,18,19,20,21 .

    RestAPI warning for Object obj = method.invoke(o,null); .

    My web.config

    SELECT TOP 1000 [id] ,[firstName] ,[lastName] ,[username] ,[password] FROM
    [AndroidAppDB].[dbo].[UserDetails]

    1,same,same,same,same

    I am trying user id : same

    password : same

    when run as android and try to user ID & password click on login LogCat
    Error : JSONParser => parseUserAuth = No value for Value.

    please help me how connect SQL server from apps

    Thanks

    • Luca Vitrini

      Have you resolved the problem??

  • khalda askar

    Firstly Thanks for this tutorial

    secondly i face this error any help ????

    W/EGL_emulation﹕ eglSurfaceAttrib not implemented
    Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6f41e40, error=EGL_SUCCESS

    • Prasad

      Hi Ahamed Ishak i too had the same problem plz. resolve i stuck up here

  • pankaj

    hi thanks to u when i deployed the handler1.ashx file to hosting panel its showing error as ok i dont understand what is it. its one problem other is when i deployed to iis and got the api after that i run the application but its giving error in do in bagckgroung method going to catch…. please help me out

  • Vikash Singh

    i want to create a android form by using this method so can u help me

  • lebryant

    Hi there, I’ve published API on public host and got stuck with Android getting json from it. It complains about not being able to convert String to JSON. After debugging, I’ve seen that a String value is an HTML String for the web-view you see on Handler1.ashx page.

    • lebryant

      Never mind, solved it.

  • saba

    how to add configuration lines?? i mean whete to palce them in web.config

  • Guest

    can anyone tell me, its urgent

  • Ben Benarjee

    hi,
    i have small doubt.can we insert data into sql database using this method.becoz i am new to android.till now i have used back end as php and mysql.in that we will insert data into data base using this way.so i got little confussed so plz help me.thanks

  • Hiren Vaghela

    hi,
    i have follow your tutorial but i am run my android project from android studio then i have select Login and put id and password at that time give folowing error: 03-17 11:00:13.723 1106-1142/restfulapiclient.tutecentral.com.restfulapiclient E/USERAuthentication 1﹕ {“interface”:”RestAPI”,”method”:”UserAuthentication”,”parameters”:{“passsword”:”hiren”,”userName”:”hiren “}}

    03-17 11:00:13.962 1106-1142/restfulapiclient.tutecentral.com.restfulapiclient E/USERAuthentication 2﹕ {“interface”:”RestAPI”,”method”:”UserAuthentication”,”parameters”:{“passsword”:”hiren”,”userName”:”hiren “}}

    in Sql server table i have enter 1 record hiren,hiren,hiren,hiren.

  • Hiren Vaghela

    this is my api address: localhost/WebAPI/Handler1.ashx

    and private final String urlString = “http://10.0.2.2/WebAPI/Handler1.ashx”;

    any one have answer please post

  • Mirza Ahsan

    I have done everything perfectly fine. But my app is not connecting with the database. The only issue i am having is that my app is not displaying department details and creating accounts. The app is not crashing in the emulator but it not displaying any data from data base. Any suggestions? maybe i am using wrong emulator.

    • Rick Anthony G Portes

      Hi Mirza did you solve your problem? I’m facing the same error right now. help pls

      • Mirza Ahsan

        no, not by this. There is another easy way that can be used. You could use sql server data base and asp.net to create web services. Theses web service can output data in json or xml. You can them in android. This approach is more practical and easy.

        • Rick Anthony G Portes

          I see I’m stuck here for this problem I think I have to try another way that is also using sql server and c# asp.net as my web service this is for our thesis actually. sir can you give a link or any tutorial that I could use for that approach you said. THANK YOU Sir.

  • Subroto

    Hi thank you for this tutorial it is really work and so helpful to me and hope to all.

  • bero

    Thanks, it’s really helpful.
    But, I have question.. Is it possible to use Google Volley instead of AsncTask? and what I should change in RestAPI.java to work with Volley??

  • Vetriselvan V

    where is the http post in above code

  • Vetriselvan V

    friends help i need to create a android app that send imei number to .net database

  • edmundo096

    Very useful tutorial.
    Got it working after some tries, because DB login issues, IIS configuration, connection string issues, opening the port on the firewall, etc.
    Thanks! I hope you manage to create more tutorials.

  • Festypat

    i see line 78. but not inseting nor login. Log.d(“AsyncLogin”, e.getMessage());

  • genina

    Very good tutorial I followed your tutorial step by step and able to output the Json Services.. But im having this error and I dont know what to do.. please help me 🙁

    • Shagufta Shaikh

      I am not sure.. but I think JSON object returning the null value… and that is happening because your query returning the null value… check the sql query…

      • miguel

        this is the solution :

        run %windir%Microsoft.NETFrameworkv4.0.21006aspnet_regiis.exe -i

  • Pir Faraz Ali

    I’m trying to store my SQL database on Cloud using Microsoft Azure. How do I upload the database there and connect it with the API?

  • Monty Nabeel

    nice tutorial , but I have problem ,, the app runs perfectly ,but when I press Dept Details the loading completes with a blank page ,, and checked the log cat says ColorBuffer::bind_fbo: FBO not complete: 0x505

  • Tom Smith

    Hi,
    Great tutorial, took a little tweaking due to the layout but fantastic, many thanks!
    One thing that is bugging me hugely, I’m trying to modify the code to allow a custom inflated xml listview. Would you be able to provide a quick example?
    Thanks,
    Tom

  • Siva KM

    Hi,
    Great tutorial,it is work without error but the data couldn’t store & retrieve from the server
    plz help me……

    • Rick Anthony G Portes

      Siva did you solve your problem? I’m facing the same problem right now I’m stuck! pls help

  • JohnColtrane

    Wonderful tutorial – works perfectly. I’ve just started Android Development and I needed to access SQL from an app. The only information I could find suggested using Java ODBC drivers, and that did not seem the most secure way. Keep up the good work.

    John.

  • Luca Vitrini

    Sorry, i think i’ve done everything right in the tutorial, and im just using your code to see if it works. However i find the same problem someone else had, when i try to access the Sql server logging or creating a new account from the app on my cell, i get on the logcat the “No value for Value” error. I did not change anything in your code, i just changed the url of course to match the site i’ve created on somee.com and the connection string, following so all of your steps.
    What could be the reason of that error? Pls Help you rule

    • Shagufta Shaikh

      I am also having the same issue.. 🙁

      • Shagufta Shaikh

        Heya…!!! I did it… Actually there was a problem in my query… I corrected it and solved the issue…. try if you can solve it…. 😀

        • Luca Vitrini

          thx, i tried to change smth and i found of the course, the same fucking error…..anyway, see far and go on 🙂

          • Rick Anthony G Portes

            Sir I’m facing the same problem right now. could you give the code of your query pls I’m stuck here. THANKS

  • mghms4

    This is great information. I don’t know if this has been answered but there are no descriptive errors returned from SQL Server within this code. I finally was able to track these errors down by adding a log command after each “String r = load(s);” command in RestAPI.java. I added “Log.d(“Errors from SQL Server: “, r);”. Whenever I had misspelled or missing DB objects, I was able to track them down pretty quickly.

  • Velmurugan Balu

    Works perfectly.Great Mr.Ahamad Ishak

  • mahmood kabi

    Thanks Ahamed Ishak
    You’ve explained was completely. It was so good. Again, thank you.

  • Pushpender Bhandari

    Thanks Nice Tutorial… (Y)

  • Akshay Patni

    Nice Tutorial. Thanks for Sharing. But, I have an issue. I always get Null Pointer Exception. Can anybody help me with this.

    • Brz

      very important…—

      did someone downloaded the APIClient.zip please send to me via mail because i couldn’t download it

      my email :hassanisaeed19@yahoo.com

  • nyiko

    good day and have anyone been able to solve this problem D/JSONParser => parseLevels(1036): No value for Value? please need hints on what part of the code i should fix

    • Mohammad

      i solved the same problem by checking my query and my connection string in visual studio, make sure you have the correct connection string for .net 4 framework,it should look like this :-

      also don’t forget to restart your web service by re-debugging the project in visual studio

      • nyiko

        Thanks for replying, the thing is my connection string and query are working because tested the results using asp.net to check the coding on the right path. my methods for levels returns a list not a DataTable, if you have time could share the code and you can give me your input where I went wrong?

        • Mohammad

          i also tested a variety of connection strings using ASP.net and all of them were ok but only the one i gave you worked properly and solved the issue of “no value for Value”, please post your code so me or other developers can try to help you 🙂

          • nyiko

            connection string

            Connection Class

            public class clsDataAccess

            {

            public SqlConnection ConTuk = new SqlConnection(@”Data Source=localhost;Initial Catalog=ETukTukFDB;Integrated Security=True”);

            public SqlCommand CommTuk;

            public SqlDataReader ReaderTuk;

            public SqlDataAdapter AdapterTuk;

            public DataTable TableTuk;

            public DataSet DataSetTuk;

            }

            method am trying to call

            public List getLevels()

            {

            clsDataAccess tukAccess = new clsDataAccess();

            tukAccess.ConTuk.Close();

            tukAccess.ConTuk.Open();

            tukAccess.AdapterTuk = new SqlDataAdapter(“select * from Levels”, tukAccess.ConTuk);

            tukAccess.TableTuk = new DataTable();

            tukAccess.AdapterTuk.Fill(tukAccess.TableTuk);

            List allLevels = new List();

            int rowCount = tukAccess.TableTuk.Rows.Count;

            for (int row = 0; row < rowCount; row++)

            {

            Levels level = new Levels();

            level.Level_ID = Convert.ToInt32(tukAccess.TableTuk.Rows[row]["Level_ID"].ToString());

            level.Level_Name = tukAccess.TableTuk.Rows[row]["Level_Name"].ToString();

            level.Level_Desciption = tukAccess.TableTuk.Rows[row]["Level_Desciption"].ToString();

            allLevels.Add(level);

            }

            tukAccess.ConTuk.Close();

            return allLevels;

            }

            thanks

          • Mohammad

            private static string conStr = ConfigurationManager.ConnectionStrings[“fezile-pc.ETukTukFDB (JSONWebAPI)”].ConnectionString;

            this how it works with me and consider changing your connection string in web.config and make it exactly as the one i gave you

          • nyiko

            thanks will work on the connection string you gave me

          • nyiko

            Finally connected and thanks for helping me mr Mohammad, The problem that I was having from my side also was that the server roles in SQL Server was denying me access, but also your connection method truly helped Thank YOU!!!

          • Mohammad

            happy it finally works for you 🙂

          • sudhir

            How did you get that ? I implemented service as shown in part1 but when I type ?Android in url Handler1.ashx is downloading instead zip file .. Can you help me out??

          • Rick Anthony G Portes

            Hey Nyiko I’m facing the same problem I’m stuck here pls give me a hand. this is my web.config

          • nyiko

            Hey Rick sorry for replying late first check your sql server roles that they allow you to connect and are you connecting via emulator using local ip address?

          • Rick Anthony G Portes

            Thanks sir you reply I’m stuck here for almost 3 days I tried everything I could but to bad I couldn’t solved d problem. Yes I’m connecting through my emulator I already access it in my emulator after publishing the JSONWebAPI my only problem now, I cannot register any account in the database and cannot login the error says No value for value in the logcat. I think the problem is my connectionstring in the web.config? I will try now to check my sql server as you said sir.

          • Rick Anthony G Portes

            Sir how did you solved your problem? I’m stuck with this no value for value pls help sir. this is my connection string.

            THANKS in advance

  • Kaleem Raza

    where to find .publishsettings when hosting it publicaly

    • krishna

      You can get publish settings in your server hosting panel.

  • krishna

    Hello Friend,
    Here is a problem in process that in first part web service created in Visual Studio,
    But in second part the code come with RestAPI.java
    It’s little bit confusing, any one can help me with this.
    I am developing a mobile app in Intel XDK, and want to store and save data in SQL server.

    Thanks in Advance…

    • sudhir

      How did you download RestAPI.java ,
      when I type ?ANdroid , I was only able to download Handler.ashx file

  • krishna

    Want to retrieve and save data in my website’s SQL Server database.
    The Intel XDK is my working environment for mobile App development, Please help me friends and ADMIN.
    Reply or drop an email 20krish@gmail.com

    Thanks in Advance…

  • Numair Qadir

    Hello @ahamedishak:disqus,
    Great tutorial. It would be great if we can have some example of Image Uploading too. I was unable to upload the image.

  • shunny

    hi bro is there another way to create connection between sql server and android app kindly tell me i did this three time n solve all the errors but till yet not solved if u have video tutorial of this kindly give me the link thanks………….

  • Muhammad Yousuf Siddiqui

    Hello,i am yousuf siddiqui
    i need ur help ,
    main real android device main ye application chala raha hun,maine hosting b kar wale but jab main department table ke activity main enter hota hun so,blank activity ate hy or when ever i want to create use account via android application wo server pe account nai banta ..maine apke saare step follow kiye but no change please help me
    Thanks

    my email i’d:messenger.sid@hotmail.com

    this is dept activity

    • Sunay

      Hi Muhammed , Did you solve this problem? I have the same error…..

  • Sunay

    Hi , It was a very good work..
    I do everything step by step but publishing error occurs.
    Thank You for help
    error as :

    type=”Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″
    Satır 18: warningLevel=”4″ compilerOptions=”/langversion:6 /nowarn:1659;1699;1701″/>

  • manoj sagar

    Awesome explanation………. Sir,

    Thank you very much for this tutorial.

    I’m trying to follow but while going through the url
    http://localhost:3742/Handler.ashx?ANDROID
    not getting save dialog so that I can save ClientAPI.zip file instead of this I’m getting Hander.ashx
    Please help me out.

    • sudhir

      Same here !! Did you resolve it???

      • Brz

        very important…

        did someone downloaded the APIClient.zip please send to me via mail because i couldn’t download it

        my email :hassanisaeed19@yahoo.com

    • Brz

      very important……

      did someone downloaded the APIClient.zip please send to me via mail because i couldn’t download it

      my email :hassanisaeed19@yahoo.com

      • nitin

        Hello @disqus_Ti3CJtrDJY:disqus Have you gotten APIClient.zip file .

        • master

          add bihind url of services ?ANDROID
          and run again Download zip file and extract it u get RestAPI.java

  • Nikhil Balyan

    my data is not storing in the database i have selected the androidappdb before firing the query but the data is not showing up there please help any help will be highly appreciated by me

  • manoj sagar

    Thank you very very much……… Lovely Tutorial , Finally I have fixed my problem now working fine. You have done a fantastic job, very nice explanation sir. You made my day… Again thank you.

    • sudhir

      How did you get that ? I implemented serviec as shown in part1 but when I type ?Android in url Handler1.ashx is downloading instead zip file .. Can you help me out??

  • Brz

    Hi Ahmad
    that’s good work
    thanks………
    I can’t download this link http://downloads.tutecentral.com/wp-content/uploads/2014/03/RestfulAPIClientExample.zip

  • Ahmad Talal Egbariya

    Thanks Ahmad For The Great Work, i have a question about the android api java file,
    in the file there is an url with my local host, does i need to change it to an internet host to make keep the functionalty of the app working when i install the app on any android device?

  • Amol Chougule

    i am getting error on getMenuInflater().inflate(R.menu.login, menu); “cannot resolve symbol login” and
    getMenuInflater().inflate(R.menu.dept, menu); “cannot resolve symbol dept” and
    getMenuInflater().inflate(R.menu.create_user, menu); “cannot resolve symbol create_user”
    please help

  • Amol Chougule

    in urlstring i was added all above ip address as well as my laptop domain ip was added but it is giving “DNS server not found” message

  • Bugra Onucyildiz

    Hello disable download ashx json file

    The android app is going to this link: “mydomain.com/jsonWebAPI/Handler1.ashx” To retrieve details and to communicate with my c# code and sql server queries.

    Now, if you add to the query string Handler1.ashx?android or ?csharp All my json class will get download as a file and the user can see my code.

    How can i prevent it ? I want to secure this web service handler.

    Thank you all.

  • nitin

    Please provide me RestAPI.java
    My email is lakhwinderk80@gmail.com

    • master

      after services are succssfull run
      add behind url ?ANDROID
      like this way

      http://clientmgt.somee.com/Handler1.ashx?Android
      and run again it will download zip file
      extract it and have you RestAPI .java File

      • lakhwinder

        Thanks for reply sir.After add this and run the application then i got this error
        { “Successful”: false, “ErrorMessage”: “Internal server error” }

        where is problem ?? please help me,

  • master

    I want to get Details from sql server databse to android app with user inputed id in edittext

  • mish

    Nice Tutorial. Thanks for Sharing. But, I have an issue. I got this error while publishing locally please help me…….

    and here is the windows features of my system

  • Banucho Cassamo

    Hi! How to generate pdf to read in android in restful?

  • ahsan butt

    how can i connect this with android real android phone??? this video confusing me

  • Ramesh Krishnan

    hi ahamed, when i run my login part i am getting invalid username and password, when i trace my code using debug option it is saying there is no value for Value(used in json parser) can you help me out from this, and find some time to explain how this is parsing the values over the network to web service, so that all others will have an idea on how it actually works

  • Ramesh Krishnan

    hi, i can see the json page if i use the 10.0.2.2 ip in emulator but login page is not working, showing invalid username and password , but i parse the correct username and password, can any one find the solution for this ASAP.—thanks

  • dipak

    Hello
    In my app there is only create new account and also stored data into sql server but in LoginActivity there is error to UserAuthentication.the error is can not resolve UserAuthentication.
    please help me
    and in my RestApi.java File there is no such method USerAuthentication please help me

  • william

    Ahamed Ishak,
    thanks for the tutorial, could you please expand it with an example where you can upload an image from the android application ?, thank you very much for considering my request….

  • Meryy

    Ahmed please could you send me the sample application file, I can’t download it
    karkouri.inpt@gmail.com

  • mohammad Bkerat

    how can i check if username is exists when i register

  • Dipaks

    Hello i have uploaded this public hosting network but whenever i am running app on real device it cant get data from It. i have added the published url as a “urlstring” please give me solution