Android gets JSON data

Source: Internet
Author: User
Tags throwable
Step One: The page returns JSON data.

Make some simple changes to the json.php code for this space log, "PHP and Ajax Simple implementations", as follows: code echo $_get[' Jsoncallback ']. ' ('. Custom_json::encode ($big _test) ';

instead echo $_get[' Jsoncallback '].custom_json::encode ($big _test);

Save the file as jsondata.php.

Step two: Write the Android code.

1. Write the contact class, set the set and get methods.

Package com.domain;

public class Contact {
private String name;
private int age;
private int sex;
Private Double height;
Private Boolean Is_human;
private string string;

Public contact () {}

Public Contact (String name, int. age, int sex, Double height,
Boolean Is_human, string string) {
THIS.name = name;
This.age = age;
This.sex = sex;
This.height = height;
This.is_human = Is_human;
this.string = string;
}
Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

public int getage () {
return age;
}

public void Setage (int.) {
This.age = age;
}

public int Getsex () {
return sex;
}

public void setsex (int sex) {
This.sex = sex;
}

Public Double getheight () {
return height;
}

public void SetHeight (Double height) {
This.height = height;
}

public Boolean Isis_human () {
return Is_human;
}

public void Setis_human (Boolean Is_human) {
This.is_human = Is_human;
}

Public String getString () {
return string;
}

public void SetString (string string) {
this.string = string;
}

}

2. Write the input Stream processing tool class Streamtools.

Package com.shao.utils;

Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;

public class Streamtools {
public static byte[] Readinputstream (InputStream instream) throws exception{
Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();
byte[] buf = new byte[1024];
int len = 0;
while (len = Instream.read (BUF))! =-1)
{
Outstream.write (buf, 0, Len);
}
byte[] data = Outstream.tobytearray ();//binary data for Web pages
Outstream.close ();
Instream.close ();
return data;

}

}

3. Write the Android layout file main.xml.

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
android:orientation= "Vertical"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
>
<textview
Android:id= "@+id/name"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>

<listview
Android:id= "@+id/listview"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
/>
</LinearLayout>

New layout file Item.xml.

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
android:orientation= "Vertical"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
>
<textview
Android:id= "@+id/name"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>
<textview
Android:id= "@+id/sex"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>

<textview
Android:id= "@+id/age"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>
<textview
Android:id= "@+id/height"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>
<textview
Android:id= "@+id/is_human"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>
<textview
Android:id= "@+id/string"
Android:layout_width= "100dip"
android:layout_height= "Wrap_content"
/>

</LinearLayout>

Add the following line to the String.xml:

<string name= "Error" >net error</string>

4. Write the business implementation class.

Package Com.shao;

Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import java.util.ArrayList;
Import java.util.List;

Import Org.json.JSONArray;
Import Org.json.JSONObject;

Import Com.domain.Contact;
Import Com.shao.utils.StreamTools;

public class MyService {

public static list<contact> Getlastcontact () throws Throwable
{
String Path = "http://192.168.1.100:8080/WebContent/testjson/jsondata.php";
list<contact> contacts = new arraylist<contact> ();
URL url = new URL (path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setconnecttimeout (5*1000);
Conn.setrequestmethod ("GET");
InputStream instream = Conn.getinputstream ();
byte[] data = Streamtools.readinputstream (instream);
String json = new string (data);
Jsonarray array = new Jsonarray (JSON);
for (int i=0;i<array.length (); i++)
{
Jsonobject item = array.getjsonobject (i);
Contact Contact = new Contact (item.getstring ("name"), Item.getint ("Age"), Item.getint ("Sex"), item.getdouble ("height" ), Item.getboolean ("Is_human"), Item.getstring ("string"));
Contacts.add (contact);
}

return contacts;
}


}

5. Write the main activity class.

Package Com.shao;

Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Com.domain.Contact;

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.widget.ListView;
Import Android.widget.SimpleAdapter;
Import Android.widget.Toast;

public class Testxml extends Activity {
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
try {
list<contact> contacts = Myservice.getlastcontact ();
list
ListView ListView = (ListView) Findviewbyid (R.id.listview);
for (contact contact:contacts)
{
hashmap<string,object> item = new hashmap<string,object> ();
Item.put ("Name", Contact.getname ());
Item.put ("Sex", contact.getsex ());
Item.put ("Age", Contact.getage ());
Item.put ("Height", contact.getheight ());
Item.put ("Is_human", Contact.isis_human ());
Item.put ("string", contact.getstring ());
Data.add (item);

}





Simpleadapter adapter = new Simpleadapter (this, data, R.layout.item,
New string[]{"name", "Sex", "age", "height", "Is_human", "String"},
New Int[]{r.id.name, R.id.sex, R.id.age, R.id.height, R.id.is_human, r.id.string});

Listview.setadapter (adapter);



} catch (Throwable e) {
LOG.E ("Shao", e.tostring ());
Toast.maketext (This, r.string.error, 1). Show ();
}
}
}



6. Turn on the access network feature.

<uses-permission android:name= "Android.permission.INTERNET"/>

Step three test.
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.