Java code:
Package com.sxt.day04_05;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.net.URLConnection;
Import COM.SXT.DAY04_05.R;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
public class Mainactivity extends Activity {
String musers;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
LOG.I ("main", "OnCreate ()");
if (savedinstancestate==null) {//If mainactivity is created for the first time
Download the Users.json file from the server
Downloadusers ();
}else{
Musers=savedinstancestate.getstring ("users");
LOG.I ("main", musers);
}
}
Download the Users.json file from the server
private void Downloadusers () {
New Thread () {//SDK requires download data from 4.0 to be performed in a worker thread
public void Run () {
InputStream in =null;
try {
URL url=new url ("Http://10.0.2.2/users.json");
URLConnection conn = Url.openconnection ();
in = Conn.getinputstream ();
Byte[] Buffer=new byte[1024];
int len = in.read (buffer);
Musers=new String (buffer, 0, Len);
LOG.I ("main", musers);
} catch (Malformedurlexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
if (in!=null) {
try {
In.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
};
}.start ();
}
@Override
protected void OnStart () {
Super.onstart ();
LOG.I ("main", "OnStart ()");
}
@Override
protected void Onresume () {
Super.onresume ();
LOG.I ("main", "Onresume ()");
}
@Override
protected void OnPause () {
Super.onpause ();
LOG.I ("main", "OnPause ()");
}
@Override
protected void OnStop () {
Super.onstop ();
LOG.I ("main", "OnStop ()");
}
@Override
protected void OnDestroy () {
Super.ondestroy ();
LOG.I ("main", "OnDestroy ()");
}
@Override
protected void Onrestart () {
Super.onrestart ();
LOG.I ("main", "Onrestatr ()");
}
@Override
protected void Onsaveinstancestate (Bundle outstate) {
Super.onsaveinstancestate (outstate);
LOG.I ("main", "Onsaveinstancestate ()");
Outstate.putstring ("Users", musers);
}
@Override
protected void Onrestoreinstancestate (Bundle savedinstancestate) {
Super.onrestoreinstancestate (savedinstancestate);
LOG.I ("main", "Onrestoreinstancestate ()");
}
}
This article from "Follow the heart of the other side" blog, declined reprint!
Save data when switching between Android's crossbar screen