this
This tutorial is presented in three parts as architecture 3-tier presented in the following figure:
To complete this tutorial we have used the
mysql database, a web server and mobile client.
In mysql I created a database named dblogin in what is called a table usertable defined by two fields (username, userpassword) all varchar (45).
Principle application
The client initiates the request to the server:
http://10.0.2.2:8080/SidibeServer/LoginUser with the connection parameters (username and password).
The server that captures this information and sends a query to the database and retrieves information that corresponds to the application (Relationship 2 and 3). by the following syntax:
\u0026lt;String username = request.getParameter ("login"); String password = request.getParameter ("password");
User user = new User (username, password);
\u0026lt;String username = request.getParameter ("login"); String password = request.getParameter ("password");
User user = new User (username, password);
At the server before sending data to the client, they put it in JSON format.
Parsing Json format : User
Our object is defined by its username and password, then we'll use the librairy json.jar to put it in this format:
public static void userToJson (User user, JSONWriter jsonWriter) throws JSONException
{
jsonWriter.object ( )
jsonWriter.key ("LoginStatus). value (" yes ");
jsonWriter.key (" username "). value (user.username)
jsonWriter.key (" userpassword " ). value (user.userpassword)
jsonWriter.endObject ();
}
data to send to the client android are now in json format. The client retrieves the flow in Json format and parses it to build our User object if not null. as shown in the following snippet:
public static User UserConnection (User user) throws Exception {
URL url = new URL (Accueil.URL_SERVER + LoginUser? login = "+ user.username +" & password = "+ user.userpassword)
System.out.println (url.toString ());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() /100 != 2) {
throw new IOException("Response not OK Version" + connection.getResponseCode());
}
InputStreamReader in= new InputStreamReader(connection.getInputStream());
BufferedReader reader= new BufferedReader(in);
StringBuffer sbf= new StringBuffer();
String line= null;
while((line=reader.readLine())!=null){
sbf.append(line);
}
jsonObject JSONObject = new JSONObject (sbf.toString ());
if (jsonObject.getString ("LoginStatus). Equals (" yes ") ) return new User (jsonObject)
return null;}
In this snippet we have built a User from JsonObject defined in the User class as shown in the following constructor code:
public User (JSONObject jsonObject) throws Exception {
/ / We test first if the user exists, it exists in the return flow we build this to avoid the NullPointerException.
if (jsonObject.get ("LoginStatus). Equals (" yes ")) {
this.username jsonObject.getString = (" username ");
this.userpassword = jsonObject. getString ("userpassword");}
Animation:
Parsing Json format : User
Our object is defined by its username and password, then we'll use the librairy json.jar to put it in this format:
public static void userToJson (User user, JSONWriter jsonWriter) throws JSONException
{
jsonWriter.object ( )
jsonWriter.key ("LoginStatus). value (" yes ");
jsonWriter.key (" username "). value (user.username)
jsonWriter.key (" userpassword " ). value (user.userpassword)
jsonWriter.endObject ();
}
data to send to the client android are now in json format. The client retrieves the flow in Json format and parses it to build our User object if not null. as shown in the following snippet:
public static User UserConnection (User user) throws Exception {
URL url = new URL (Accueil.URL_SERVER + LoginUser? login = "+ user.username +" & password = "+ user.userpassword)
System.out.println (url.toString ());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() /100 != 2) {
throw new IOException("Response not OK Version" + connection.getResponseCode());
}
InputStreamReader in= new InputStreamReader(connection.getInputStream());
BufferedReader reader= new BufferedReader(in);
StringBuffer sbf= new StringBuffer();
String line= null;
while((line=reader.readLine())!=null){
sbf.append(line);
}
jsonObject JSONObject = new JSONObject (sbf.toString ());
if (jsonObject.getString ("LoginStatus). Equals (" yes ") ) return new User (jsonObject)
return null;}
In this snippet we have built a User from JsonObject defined in the User class as shown in the following constructor code:
public User (JSONObject jsonObject) throws Exception {
/ / We test first if the user exists, it exists in the return flow we build this to avoid the NullPointerException.
if (jsonObject.get ("LoginStatus). Equals (" yes ")) {
this.username jsonObject.getString = (" username ");
this.userpassword = jsonObject. getString ("userpassword");}
Animation:
many developers have habitutde display a dialog box when the password or login are incorrect.
Unlike them, so the application can inherit the behavior of its developer, I found a great idea that even someone who can not read can understand.
The idea is to opine on EditText when the password or username is incorrect. By entering a wrong password, you will see the EditText say no by nodding like a man who said no.
For this we created an animation that will be applied to our EditText:
The file is called editanim.xml
}
Database:
Here simply Schematic our database represented in the following figure:
And in this table we have inserted some test data which are:
With a simple application we get the data in dblogin simply.
Server:
Our server is a web applicatio tomcat.
We created a model with a User class attributes (username and userpassword)
This class is simply to have the form of a model.
ModelToJsonFormat Class: This class is simply used to parse the object into json. It contains a static method. I prefer simply to separate the ethics code.
following contents:
package com.sidibe.blog.android.help.tool;
import org.json.JSONException;
import org.json.JSONWriter ;
import com.sidibe.blog.android.help.server.model.User;
/**
* Containt only an static method.
* @author JBromo
*
*/
public class ModelToJsonFormat {
/**
* This method take an object user and parset it with JsonWriter
* @param user : User to parse an json format
* @param jsonWriter : Writer to use for parsins
* @throws JSONException
*/
public static void userToJson(User user, JSONWriter jsonWriter) throws JSONException
{
jsonWriter.object();
jsonWriter.key("loginStatus").value("yes");
jsonWriter.key("username").value(user.username);
jsonWriter.key("userpassword").value(user.userpassword);
jsonWriter.endObject();
}}
LoginUser Class: This class performs all the transaction class and is the only useful and necessary.
package com.sidibe.blog.android.help.server.service;
import java.io.IOException;
import java.sql.Connection;
import java.sql. DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http. HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONWriter;
import com.sidibe.blog.android.help.server.model.User;
import com.sidibe.blog.android.help.tool.ModelToJsonFormat;
import com.sidibe.blog.android.help.tool.ShareData;
/**
*
* @author JBromo
*
*/
public class LoginUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginUser() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username=request.getParameter("login");
String password=request.getParameter("password");
User user= new User(username, password);
System.out.println(user.toString());
JSONWriter writer = new JSONWriter(response.getWriter());
try {
User usr=this.testUserLogin(user);
//Check is user is null. Because if user is name.
if(usr==null)
{
// If user is null we send and string to let know user is null
writer.object();
writer.key("loginStatus").value("no");
writer.endObject();
}
else
{
// Else user is not null parse it
// Transforme a model user to parson object
ModelToJsonFormat.userToJson(user, writer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get an Instance SQL connection
* @return Object Connection
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
* @throws SQLException
*/
private Connection getConnect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection("jdbc:mysql://"+ShareData.address+"/"+ShareData.DBLOGIN, ShareData.DBNAME, ShareData.DBPASSWORD);
}
/**
* Verifie the user parameter if its correct
* @param user : User to checik
* @return the user checket
* @throws Exception
* @throws IllegalAccessException
* @throws ClassNotFoundException
* @throws SQLException
*/
private User testUserLogin(User user) throws Exception, IllegalAccessException, ClassNotFoundException, SQLException
{
// The table name is : usertable and it has two columm : username and userpassword
User usr= null;
String requestSQL="select *from usertable where username='"+user.username+"' and userpassword='"+user.userpassword+"'";
Connection connection= getConnect();
Statement statement =connection.createStatement();
ResultSet resultSet= statement.executeQuery(requestSQL);
while(resultSet.next())
{
// the get User parameter in the database
usr = new User (resultSet.getString ("username"), resultSet.getString ("userpassword"));}
return usr;}
}
The client application:
In the client application, in addition to the makeup required, (layout, events, activities, and other), there is User simply a model whose constructor takes a json object and builds with it.
Here this class:
package com.sidibe.blog.android.model;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author JBromo
*
*/
public class User {
public String username;
public String userpassword;
public User(String username, String userpassword) {
super();
this.username = username;
this.userpassword = userpassword;
}
public User(JSONObject jsonObject) throws Exception {
if(jsonObject.get("loginStatus").equals("yes"))
{
this.username=jsonObject.getString("username");
this.userpassword= jsonObject.getString("userpassword");
}
}
}
Client:
The main activity carried out with the handler and the thread to make the connection is defined in the Home class. This class extends from Activity is basically the interface that allows the connection.
package com.sidibe.blog.android.home;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import com.sidibe.blog.android.model.User;
public class Accueil extends Activity {
public static final String URL_SERVER="http://10.0.2.2:8080/SidibeServer/";
public static final int SUCCES=1;
public static final int ECHEC=-1;
public static final int CONNECTION_EXCEPTION=0;
public User user;
EditText mail;
EditText password;
public Animation errorAnimation=null;
public ProgressDialog connectionloading;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interface1);
connectionloading= new ProgressDialog(this);
connectionloading.setCancelable(true);
final UserLoaderHandler userLoaderHandler= new UserLoaderHandler(this);
mail= (EditText)findViewById(R.id.edit_mail);
password = (text edit) findViewById (R.id.edit_password)
Button connect = (Button) findViewById (R.id.bt_connect)
, error = AnimationUtils.loadAnimation animation (this, R.anim.editextanim)
connect.setOnClickListener ( View.OnClickListener new () {
public void onClick (View v) {
final userX User = new User (mail.getText (). toString (), password.getText (). toString ());
connectionloading ProgressDialog.show = (v.getContext (), "Waiting Connection", "Connection");
Accueil.testUserConnection (userX, userLoaderHandler);
}});}
public static User userConnect(User user) throws Exception
{
URL url = new URL(Accueil.URL_SERVER + "LoginUser?login=" +user.username+"&password="+user.userpassword);
System.out.println(url.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() /100 != 2) {
throw new IOException("Response not OK Version" + connection.getResponseCode());
}
InputStreamReader in= new InputStreamReader(connection.getInputStream());
BufferedReader reader= new BufferedReader(in);
StringBuffer sbf= new StringBuffer();
String line= null;
while((line=reader.readLine())!=null){
sbf.append(line);
}
JSONObject jsonObject = new JSONObject(sbf.toString());
if(jsonObject.getString("loginStatus").equals("yes")) return new User(jsonObject);
return null;
}
public static void testUserConnection(final User user,final Handler receiver) {
new Thread () {
public void run () {
try {
Users users = Accueil.userConnect (user);
Message.obtain Message msg = ();
if (users! = null) {
msg.arg1 = Accueil.SUCCES;
msg.obj = users ;
}
else
{
msg.arg1 = Accueil.ECHEC;
}
receiver.sendMessage (msg);
} catch (Exception e) {
Message.obtain Message msg = ();
msg.arg1 = CONNECTION_EXCEPTION;
msg.obj = e;
e.printStackTrace ();
receiver.sendMessage (msg);}
}}. Start ();}
private UserLoaderHandler class extends Handler {
private Context parent;
public UserLoaderHandler (Context parent) {
super ();
this.parent = parent;
} Public void
handleMessage (Message msg) {
connectionloading.dismiss ();
switch (msg.arg1) {
case Accueil.SUCCES:
user = (User) msg.obj;
break;
case Accueil.ECHEC:
mail . startAnimation (errorAnimation);
password.startAnimation(errorAnimation);
break;
case Accueil.CONNECTION_EXCEPTION :
Exception e = (Exception) msg.obj;
e.printStackTrace();
Builder builder = new AlertDialog.Builder(parent);
builder.setTitle("Echec de connection ");
builder.setMessage("Netword connection problem");
builder.show ();
break;}
}}
}