toggle Cinema 14 Jun 2010

Reading a json login response with Android SDK Posted by Insane in Uncategorized | 22 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
toggle Cinema 14 Feb 2010

When Twitter and Facebook meets Greasemonkey !! Posted by Insane in Javascript | No responses

He estado haciendo muchas cosas, algunas de ellas sin sentido he de admitirlo, pero al fin y al cabo solo cosas. Anyway, acabo de hacer dos scripts para greasemonkey que espero sean de utilidad para alguien.

20091502_91mrrgxr

  • FullTwitter se encarga de reescribir la interfaz de twitter expandiéndola al 100% y sumándole algunos features, puedes descargarlo aquí.
  • FullFacebook jeje, bueno este es mas para aquellas personas que al igual que yo odian que el nuevo layout de esta red social no use todo el canvas del html. [descargar full_facebook.user]

No esta de más recordarte que debes tener instalado Greasemonkey.

  • Share/Bookmark
toggle Cinema 12 Feb 2010

¿Una sombra sobre la realidad aumentada en México? Posted by Insane in Actionscript x.x, Publicidad Digital | 35 responses

¿Una losa cae sobre la realidad aumentada en México?
El día de hoy casi cualquier cosa puede ser registrada en el IMPI, pues ahora resulta que una empresa llamada Eria Realidad Aumentada (http://www.realidadaumentada.com.mx/), no sólo registro el nombre de “Realidad aumentada” si no la filosofía o proceso que inmiscuye la realidad aumentada en sí, usando cualquier tecnología dígase Flarttoolkit, Artoolkit,  D’fusion, o un motor que cualquier de nosotros pudiéramos crear.
Este tipo de acciones sin lugar a duda dan un fuerte golpe a la creatividad y al progreso de la publicidad digital y el uso de la tecnología en México; obviamente el uso de la realidad aumentada no es indispensable -por ahora- para crear aplicaciones interactivas, no obstante este afán por apropiarse de todo daña terriblemente  el  mercado interactivo.
Hoy pudimos ver con nuestros  propios  ojos un documento del  IMPI donde dicha empresa era propietaria de esta filosofía (aplicada con cualquier tecnología) en México. Ahora me pongo a pensar, esto no solo nos afecta a las agencias digitales que en algún momento determinado podríamos necesitar acceder a este tipo de tecnologías, dentro de poco saldría el Project Natale y algunos otros periféricos y electrodomésticos que cuestan con esas tecnologías, ¿ellos también se llevarán el fiasco que alguien ya lo registró y tendrán que pagar?
Propongo que todas las agencias interactivas en México y asociaciones a fin como IAB, AMPCI pongamos cartas en el asunto y demostremos que esta filosofía no puede ser patentada, de hecho universidades como IPN y UNAM tienen 4 años trabajando con estos conceptos, ¿cómo puede alguien a registrarlo ahora?

El día de hoy casi cualquier cosa puede ser registrada en el IMPI y es que la poca o inexistente cultura digital que existe en nuestro país abre las puertas a lo ilógico. ¿ a que viene esto ?  pues resulta que una empresa llamada Eria Realidad Aumentada (http://www.realidadaumentada.com.mx/), no sólo registro el nombre de “Realidad aumentada” si no la filosofía o proceso que inmiscuye la realidad aumentada en sí, usando cualquier tecnología dígase Flarttoolkit, Artoolkit,  D’fusion, o un motor que cualquier de nosotros pudiéramos crear.

Este tipo de acciones sin lugar a duda dan un fuerte golpe a la creatividad y al progreso de la publicidad digital y el uso de la tecnología en México; obviamente el uso de la realidad aumentada no es indispensable -por ahora- para crear aplicaciones interactivas, no obstante este afán por apropiarse de todo daña terriblemente  el  mercado interactivo.

Hoy pudimos ver con nuestros  propios  ojos un documento del  IMPI donde dicha empresa era propietaria de esta filosofía (aplicada con cualquier tecnología) en México. Ahora me pongo a pensar, esto no solo nos afecta a las agencias digitales que en algún momento determinado podríamos necesitar acceder a este tipo de tecnologías, dentro de poco saldría el Project Natale y algunos otros periféricos y electrodomésticos que cuestan con esas tecnologías, ¿ellos también se llevarán el fiasco que alguien ya lo registró y tendrán que pagar?

En mi opinión, este evento presenta un retroceso enorme hacía un Interactive cada vez más innovadora, imaginar que en adelante todas las ideas revolucionarias serán opacadas por patentes generales  me hace darme cuenta que aun no hemos avanzado tanto camino como creemos. La publicidad mexicana tiene sed de creatividad, es por eso que bloquear los recursos que pueden sacarla de ese estado no es  más que  un golpe directo a todos aquellos que intentamos día a día llevar  un mensaje usando la tecnología  como medio de comunicación.

67292.strip1

Propongo que todas las agencias interactivas en México y asociaciones a fin como IAB, AMPCI pongamos cartas en el asunto y demostremos que esta filosofía no puede ser patentada, de hecho universidades como IPN y UNAM tienen 4 años trabajando con estos conceptos, ¿cómo puede alguien a registrarlo ahora?

legal2

Update

[13/02/2010] Hemos escrito a ARToolworks que son las personas con derechos exclusivos para vender licencias comerciales de FLARToolKit , comentándoles sobre este gran problema nos han dejado publicar este correo como una respuesta de su parte.

Hi Oscar, Thanks for the email. I’m not sure what effect this patent will have. I know for sure that people were doing web camera based Augmented Reality in Mexico for at least 8 years, so there is a lot of prior art that could be pointed to that may invalidate their patent.

FLARToolKit was originally developed in Japan and so may also be outside the domain of the patent as well.


  • Share/Bookmark