Java Handler

A Handler is an Android class you can use to schedule code that should be run at some point in the future.  You can also use it to post code that needs to run on a different thread.

To use the Handler, you wrap the code you wish to schedule in a Runnable object, and then use the Handler post() and postDelayed() methods to specify when you want the code to run.

post()
The post() method posts code that needs to be run as soon as possible (which is usually almost immediately). The post() method takes one parameter, an object of type ‘Runnable’. A ‘runnable’ is simply a job you want to run, just like in Java. You put the code you want to run in the Runnable’s run() method, and the Handler will make sure the code is run as soon as possible. E.g:

final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
//code to be executed is put here
}

postDelayed()
The postDelayed() method works in a similar way to the post() method except that you use it post code that should be run in the future. The postDelayed() method takes two parameters: a Runnable and a long. The Runnable contains the code you want to run in its run() method, and the long specifies the number of milliseconds you wish to delay the code by. The code will run as soon as possible after the delay. E.g:

handler.postDelayed(Runnable, long);//long is milliseconds delay before code is executed

 

Android AsyncTask

This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

To use AsyncTask you extend your class with: AsyncTask<ParamsProgressResult>.

Where:

Params is an array of inputs sent in when the AsyncTask is called.

Progress is the progress of the AsyncTask. This is used if you are displaying a progress bar.

Result is the type of result the AsyncTask will return.

 

The AsyncTask has four subclasses:

onPreExecute: action to be done before the main task.

doInBackground: the main task that is to be performed. This method signature looks like:

protected Result doInBackGround(Params...params){}

Within the doInBackground method you may want to access the individual arguments sent in. As ‘params’ is an array of arguments, you can access the individual arguments sent in with: params[index]. If only one argument is sent in then it will be: params[0]

This method always returns something.

onProgressUpdate: used for the progress display.

onPostExecute: action to be performed after the main task has been completed. Often this method uses the returned data from the doInBackground method. This method signature is:

protected void onPostExecute(Result name){}

 

If you have a class:

private class myClass extends AsyncTask<String, void, String>{}

To execute the Async task on a this class:

myClass().execute(arg1, arg2,...);

Serializable

Serialization is simply turning an existing object instance into a byte array. After a serialized object has been written into a file, it can be read from the file and deserialized. This the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

public final void writeObject(Object x) throws IOException
This method serializes an Object and sends it to the output stream.

public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

Employee class

public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;

public void mailCheck()
{
System.out.println("Mailing a check to " + name + " " + address);
}
}

Serialize Class

import java.io.*;

public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;

try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}//SerializeDemo

DeserializeDemo Class

import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}//DeserializeDemo

Read data stream into StringBuilder (Java)

To read a data stream into a string builder use the following code:


StringBuffer readInput(String sInputSream){
String url = "https://website.com";
URL obj = null;
 try {
 obj = new URL(url);
 } catch (MalformedURLException e) {
 e.printStackTrace();
 }
HttpURLConnection con = null;
 try {
 con = (HttpURLConnection) obj.openConnection();
 } catch (IOException e) {
 e.printStackTrace();
 }
BufferedReader in = null;
 try {
 in = new BufferedReader(
  new InputStreamReader(con.getInputStream()));
 } catch (IOException e) {
 e.printStackTrace();
 }
String inputLine;
StringBuffer response = new StringBuffer();

 try {
 while ((inputLine = in.readLine()) != null) {
 response.append(inputLine);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 try {
 in.close();
 } catch (IOException e) {
 e.printStackTrace();
 }

//print result
System.out.println(response.toString());
return response;
}

(This code uses ‘BufferedReader‘ which reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
In this example we use a buffer size of 8.

The ‘InputStreamReader‘ is also used. This method is a bridge from byte streams to character streams.
It reads bytes and decodes them into characters using a specified charset. In this case we use the iso-8859-1
charset.)

Reading data stream into a StringBuilder (Android)

To read a data stream into a string builder use the following code:


BufferedReader reader = new BufferedReader(new InputStreamReader(sInputStream, "iso-8859-1"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}sInputStream.close();
sRawString = stringBuilder.toString();

(This code uses ‘BufferedReader‘ which reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
In this example we use a buffer size of 8.

The ‘InputStreamReader‘ is also used. This method is a bridge from byte streams to character streams.
It reads bytes and decodes them into characters using a specified charset. In this case we use the iso-8859-1
charset.)

Android HttpClient

 

 

To use HttpClient in Android to get data from a webpage:

 

String url = "www.whateverWebPageYouWant.com";

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);

HttpEntity httpEntity = httpResponse.getEntity();

sInputStream = httpEntity.getContent();

 

The way I remember these commands is with the acronym: cpr e.g.

c = defaulthttpClient

p = httpPost

r = httpResponse

e = httpEntity

g = Getcontent

 

With this done you can use a ‘reader‘ to read the data in sInputStream.

 

You can combine the this code with the ‘reader’ code and use them as a JSON parser.