toggle Cinema 14 Jun 2010

Reading a json login response with Android SDK Posted by Insane in Uncategorized | 23 responses

androidJson had became quickly my favorite and more comfortable way to output the data, because of the simplicity of convert any data type into this type of representation. Two weeks ago I had the need to read a json server response from within an android application, althought this should be quite  straight forward in any language,  I couldn´t help to feel a little misplaced since I haven´t touched the sdk in a long time.

The problem is as follow:

  • We need to send a HTTP request to the server passing username and password in order to get the response. this must be done by a click button.
  • Once we got the response we need to parse it into a json object.
  • If the response was right then store the user and login values into the preferences.

android_login

And this is the code, hope it helps.

Layout : Generic login screen ( see reference )

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <TextView android:id="@+id/welcome_text"
    	android:text = "Welcome to My Application!n"
    	android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerHorizontal="true"
    	/>

    <TextView android:id="@+id/username_text"
    	android:text = "username:"
    	android:layout_centerHorizontal="true"
    	android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_below="@+id/welcome_text"
    	/>

    <EditText android:id="@+id/txt_username"
              android:layout_height="wrap_content"
              android:layout_width="250px"
              android:layout_centerHorizontal="true"
              android:layout_below="@+id/username_text"
              android:singleLine="true" /> 

    <TextView android:id="@+id/password_text"
    	android:text = "password:"
    	android:layout_centerHorizontal="true"
    	android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_below="@+id/txt_username"
    	/>

    <EditText android:id="@+id/txt_password"
    		  android:password="true"
              android:layout_height="wrap_content"
              android:layout_width="250px"
              android:layout_centerHorizontal="true"
              android:layout_below="@+id/password_text"
              android:singleLine="true" /> 

	<Button android:id="@+id/login_button"
		android:text="Login!"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerHorizontal="true"
		android:layout_below="@+id/txt_password"
		/>

</RelativeLayout>

Code : Json Client

package com.instropy.androiddexamples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class RestJsonClient {

    public static JSONObject connect(String url)
    {

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;

        JSONObject json = new JSONObject();

        try {
            response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                json=new JSONObject(result);

                instream.close();
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return json;
    }
    /**
     *
     * @param is
     * @return String
     */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}

Code : Front Activity

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class RestClient {
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONObject json = new JSONObject();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
json=new JSONObject(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
/**
*
* @param is
* @return String
*/
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
package com.instropy.androiddexamples;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.instropy.androiddexamples.net.RestJsonClient;

// implements OnClickListener so we don´t have to create a nested class << #ugly

public class HelloAndroid extends Activity implements OnClickListener {

private static final int SERVER_PORT = 80;

private static final String DEB_TAG = "Json_Android";

private String SERVER_HOST="instropy.com";

public static final String PREFS_NAME = "HelloAndroidPREFS";

private SharedPreferences settings;

private ProgressDialog progress;       

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

super.onCreate(icicle);

// Restore preferences

settings = getSharedPreferences(PREFS_NAME, 0);

// load up the layout

setContentView(R.layout.main);

// get the button resource in the xml file and assign it to a local variable of type Button

Button login = (Button)findViewById(R.id.login_button);

Log.i(DEB_TAG,"onCreate");

login.setOnClickListener(this);

setUserNameText(settings.getString("Login", ""));

setPasswordText(settings.getString("Password", ""));

}

public void setUserNameText(String $username){
EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
usernameEditText.setText($username);
}

public void setPasswordText(String $username){
EditText passwordEditText = (EditText) findViewById(R.id.txt_password);
passwordEditText.setText($username);

}

/*

* (non-Javadoc)

* @see android.view.View.OnClickListener#onClick(android.view.View)

*/

public void onClick(View v) {

//Handle based on which view was clicked.

Log.i(DEB_TAG+" onClick ","onClick");

// this gets the resources in the xml file

//and assigns it to a local variable of type EditText

EditText usernameEditText = (EditText) findViewById(R.id.txt_username);

EditText passwordEditText = (EditText) findViewById(R.id.txt_password);

// the getText() gets the current value of the text box

// the toString() converts the value to String data type

// then assigns it to a variable of type String

String sUserName = usernameEditText.getText().toString();

String sPassword = passwordEditText.getText().toString();

//call the backend using Get parameters (discouraged but works good for this exampl ;)  )

String address = "http://"+SERVER_HOST+":"+SERVER_PORT+"/jbackend.php?action=login&Login="+sUserName+"&Password="+sPassword+"";

if(usernameEditText == null || passwordEditText == null){
// show some warning
}else{
// display the username and the password in string format
try {

showBusyCursor(true);

progress = ProgressDialog.show(this,

"Please wait...", "Login in process", true);

Log.i(DEB_TAG, "Username: " + sUserName + "nPassword: " + sPassword);

Log.i(DEB_TAG, "Requesting to "+address);

JSONObject json = RestJsonClient.connect(address);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

showBusyCursor(false);

}//end try

progress.dismiss();

SharedPreferences.Editor editor = settings.edit();
editor.putString("Login", sUserName);
editor.putString("Password", sPassword);
editor.commit();
showBusyCursor(false);

next();

}//end else

}//end OnClick

/*

*

*/

private void showBusyCursor(Boolean $show){
setProgressBarIndeterminateVisibility($show);
}

private void next(){
// you can call another activity by uncommenting the above lines
//Intent myIntent = new Intent( this.getBaseContext() , LoggedActivity.class);
//startActivityForResult(myIntent, 0);
}

}

Update

As of the write of this post I`ve received several comments telling me to use a SSL connection , the aim of this post is just to show the concept proof  of how to connect your interface to the backend using android and json, you can use this source code as you want but keep in mind use a secure connection for the login for god sake.

Here´s a good link to begin http://java.sun.com/developer/technicalArticles/Security/secureinternet/

  • Share/Bookmark

Tags: ,

Promote this post

Would you like to add this post to your bookmarks? Come on, do not miss any updates and stay tuned.
Please share with us!
+

23 Comments to “ Reading a json login response with Android SDK ”

  1. I have Error in line 145 and 146=====>
    145.editor.putString(”Login”, (String) user.get(”Login”));
    146.editor.putString(”Password”, (String) user.get(”Password”));
    at the command “user.get”

  2. @SHADOW : Can you provide the error message?

  3. @Insane

    I am getting this error too;
    145.editor.putString(”Login”, (String) user.get(”Login”));
    146.editor.putString(”Password”, (String) user.get(”Password”));
    at the command “user.get”

    the error says that “user cannot be resolved”

  4. Apologies, my mistake . despite everything was ok after the server backend call, those lines stores Login and Password into the SharedPreferences object for the next time that user open the app.

    Change by:

    editor.putString(”Login”, sUserName );
    editor.putString(”Password”, sPassword );

    Thanks for notice it.

  5. Sir, can u please send me a complete coding for login using database ,,,
    i am new to android development sir,
    i’m creating application in android it contain registration form ,, in that registration form i want to register password and other two questions ,, it should store in database . and i have created the login form here only we should enter a password ,, it has to check from the database which is stored in the database ,,
    can u please give some coding for this ,,
    its urgent

  6. pretty cool.. thanks I’m new to all this and hopefully
    this will lead to me finally getting somewhere…

  7. Where does the code Json client go? SRC?

    or on the server?

  8. What would you do if your Content Type is xml?

  9. Whell, in that case you´d need to parse that xml by your own, take a look at this link:

    http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html

  10. mounitha May 16, 2011

    hi
    iam geting an error in line number 132 which is catch (JSONException e)

    Can anyone help me

    Thanks in advance

  11. Great example, thanks. In my case a client was providing JSON via the HTTP header so I needed to change to do the following:

    response = httpclient.execute(httpget);
    Header jsonHeader = response.getFirstHeader(”X-Json”);
    String jsonValue = jsonHeader.getValue();

  12. I have Error in line
    007:import com.instropy.androiddexamples.net.RestJsonClient;

    error message: import com.instropy.androiddexamples.net.RestJsonClient cannot be resolved

  13. can u mail me the compelte source code..i will be very thankful..
    Mi ID is eagle.usmans@gmail.com

  14. Hi i want to display thesuccessful status code ,if user logged in by using correct account else it should dispaly failure status code

  15. help me how to do that

  16. i want to do this by using httppost

  17. Sakthivel October 5, 2011

    I am getting error in JSON Client class. Please let me correct and give working code

  18. Dear Sir, can u please send me a complete coding for login using database ,,,
    i am new to android development sir,
    i’m creating application in android it contain registration form ,, in that registration form i want to register password and other two questions ,, it should store in database . and i have created the login form here only we should enter a password ,, it has to check from the database which is stored in the database ,,
    can u please give some coding for this ,,
    its urgent

  19. prafull patel November 29, 2011

    i have error in line no:132,133
    error name is unreachable catch block for JSONException.This excepation is never thown from the try
    statement body :-remove catch cluse and replace catch catch with throws.

  20. hi.
    when i hit the login url and i want to use to use this cookies in other url, how i done it????

  21. carlos ochoa February 9, 2012

    cordial saludo

    soy nuevo desarrollando en android y solicito un poco de ayuda, tengo el siguiente código para un login, el archivo se llama login2.java

    package com.android.login2;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AutoCompleteTextView;
    import android.widget.Button;
    import android.widget.Toast;

    public class Login2 extends Activity
    {
    AutoCompleteTextView user;
    AutoCompleteTextView pass;
    Button validar;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    user = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    pass = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
    validar = (Button) findViewById(R.id.button1);

    validar.setOnClickListener(new OnClickListener()
    {

    @Override
    public void onClick(View v)
    {
    ArrayList parametros = new ArrayList();
    parametros.add(”Usuario”);parametros.add(user.getText().toString());
    parametros.add(”Contrasena”);parametros.add(pass.getText().toString());

    // Llamada a Servidor Web PHP
    try
    {
    Post post = new Post();
    JSONArray datos = post.getServerData(parametros,”http://10.0.2.2/login.php”);

    // No se puede poner localhost, carga la consola de Windows
    // y escribe ipconfig/all para ver tu IP
    if (datos != null && datos.length() > 0)
    {
    JSONObject json_data = datos.getJSONObject(0);
    int numRegistrados = json_data.getInt(”id_usuario”);

    if (numRegistrados > 0)
    {
    Toast.makeText(getBaseContext(),”Usuario correcto. “, Toast.LENGTH_LONG).show();
    nextMenu();
    }

    }
    else
    {
    Toast.makeText(getBaseContext(),”Usuario o Contraeña incorrectos.”, Toast.LENGTH_LONG).show();
    }

    }
    catch (Exception e)
    {
    Toast.makeText(getBaseContext(),”Error al conectar con el servidor. “,Toast.LENGTH_LONG).show();

    }
    // FIN Llamada a Servidor Web PHP

    }
    });
    }

    class Post
    {
    private InputStream is = null;
    private String respuesta = “”;
    private void conectaPost(ArrayList parametros, String URL)
    {
    ArrayList nameValuePairs;
    try
    {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);
    nameValuePairs = new ArrayList();
    if (parametros != null)
    {
    for (int i = 0; i < parametros.size() – 1; i += 2)
    {
    nameValuePairs.add(new BasicNameValuePair((String)parametros.get(i), (String)parametros.get(i + 1)));
    }
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    }
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }
    catch (Exception e)
    {
    Log.e("log_tag", "Error in http connection " + e.toString());
    }
    finally
    {

    }
    }
    private void getRespuestaPost()
    {
    try
    {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    {
    sb.append(line + "\n");
    }
    is.close();
    respuesta = sb.toString();
    Log.e("log_tag", "Cadena JSon " + respuesta);
    }
    catch (Exception e)
    {
    Log.e("log_tag", "Error converting result " + e.toString());
    }
    }
    @SuppressWarnings("finally")
    private JSONArray getJsonArray()
    {
    JSONArray jArray = null;
    try
    {
    jArray = new JSONArray(respuesta);
    }
    catch (Exception e)
    {

    }
    finally
    {
    return jArray;
    }
    }

    public JSONArray getServerData(ArrayList parametros, String URL)
    {
    conectaPost(parametros, URL);
    if (is != null)
    {
    getRespuestaPost();
    }
    if (respuesta != null && respuesta.trim() != “”)
    {
    return getJsonArray();
    }
    else
    {
    return null;
    }
    }

    }
    private void nextMenu()
    {

    Intent i= new Intent();
    i.setClass(this, reportes.class);
    startActivity(i);

    }
    el problema es que cuando le doy validar, me muestra primero el mensaje de “usuario correcto” pero no me lleva al siguiente formulario reportes.xml y enseguida muestra el mensaje “Error al conectar con el servidor”.

    este es el código php

    if (!$link) {
    die(’No pudo conectar: ‘ . mysql_error());
    }

    mysql_select_db(”prueba”);

    $q=mysql_query(”SELECT user FROM log_in WHERE user=’{$user}’ AND password=’{$pass}’”);

    while($e=mysql_fetch_assoc($q))

    $output[]=$e;

    print(json_encode($output));

    mysql_close($link);

    ?>

    agradecería enormemente su ayuda.

  22. hey I am getting classnotfoundexception for RestJsonClient even though it is present in source code.. can anyone please help

  23. sir.. please help us out..! we are new in android and project manager has asked us to connect our login screen to http, so please tell me how to do this…. please

Leave a Reply ( Guest )

(*)

(will not be published) (*)

*