Thursday, March 10, 2011

Reading a json login response with Android SDK

Layout : Generic login screen

 
<?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

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

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 <img src="http://www.instropy.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">  )

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

}

 URL:http://www.instropy.com/2010/06/14/reading-a-json-login-response-with-android-sdk/

 

No comments:

Post a Comment