Android client obtains json data from the server and parses the implementation code

Source: Internet
Author: User

First, the client obtains json data from the server.

1. Use HttpUrlConnection

Copy codeThe Code is as follows :/**
* Get an array from the specified URL
* @ Param urlPath
* @ Return
* @ Throws Exception
*/
Public static String readParse (String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
Byte [] data = new byte [1024];
Int len = 0;
URL url = new URL (urlPath );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
InputStream inStream = conn. getInputStream ();
While (len = inStream. read (data ))! =-1 ){
OutStream. write (data, 0, len );
}
InStream. close ();
Return new String (outStream. toByteArray (); // get the written data through out. Stream. toByteArray
}

2. Use HttpClient

Copy codeThe Code is as follows :/**
* Access the database and return a JSON data string
*
* @ Param params parameters passed to the server
* @ Param url
* @ Return
* @ Throws Exception
*/
Public static String doPost (List <NameValuePair> params, String url)
Throws Exception {
String result = null;
// Obtain the HttpClient object
HttpClient httpClient = new DefaultHttpClient ();
// Create an HttpPost object
HttpPost httpPost = new HttpPost (url );
If (params! = Null ){
// Set the character set
HttpEntity entity = new UrlEncodedFormEntity (params, HTTP. UTF_8 );
// Set the parameter object
HttpPost. setEntity (entity );
}

/* // Connection timeout
HttpClient. getParams (). setParameter (
CoreConnectionPNames. CONNECTION_TIMEOUT, 3000 );
// Request timeout
HttpClient. getParams (). setParameter (CoreConnectionPNames. SO_TIMEOUT,
(3000 );*/
// Obtain the HttpResponse instance
HttpResponse httpResp = httpClient.exe cute (httpPost );
// Determine whether the request is successful
If (httpResp. getStatusLine (). getStatusCode () = 200 ){
// Obtain the returned data
Result = EntityUtils. toString (httpResp. getEntity (), "UTF-8 ");
} Else {
Log. I ("HttpPost", "HTTP POST request failed ");
}

Return result;
}

Second, Json data parsing:
Json data: [{"id": "67", "biaoTi": "G", "logo": "http://www.nuoter.com/wtserver/resources/upload/13508741845270.png", "logoLunbo": "http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg ", "yuanJia": "0", "xianJia": "0" },{ "id": "64", "biaoTi": "444", "logo ": "http://www.nuoter.com/wtserver/resources/upload/13508741704400.png", "logoLunbo": "http: // 172.16.1.75: 8080/wtserver/resources/upload/135087000038500.png"," yuanJia ":" 0 "," xianJia ": "0" },{ "id": "62", "biaoTi": "jhadasd", "logo": "http://www.nuoter.com/wtserver/resources/upload/13508741500450.png", "logoLunbo": "http: // 172.16.1.75: 8080/wtserver/resources/upload/135087415572.16.png", "yuanJia": "1", "xianJia": "0"}]

Copy codeThe Code is as follows :/**
* Resolution
*
* @ Throws JSONException
*/
Private static ArrayList <HashMap <String, Object> Analysis (String jsonStr)
Throws JSONException {
******************* ****/
JSONArray jsonArray = null;
// Initialize the list array object
ArrayList <HashMap <String, Object> list = new ArrayList <HashMap <String, Object> ();
JsonArray = new JSONArray (jsonStr );
For (int I = 0; I <jsonArray. length (); I ++ ){
JSONObject jsonObject = jsonArray. getJSONObject (I );
// Initialize the map array object
HashMap <String, Object> map = new HashMap <String, Object> ();
Map. put ("logo", jsonObject. getString ("logo "));
Map. put ("logoLunbo", jsonObject. getString ("logoLunbo "));
Map. put ("biaoTi", jsonObject. getString ("biaoTi "));
Map. put ("yuanJia", jsonObject. getString ("yuanJia "));
Map. put ("xianJia", jsonObject. getString ("xianJia "));
Map. put ("id", jsonObject. getInt ("id "));
List. add (map );
}
Return list;
}

Finally, data adaptation:

1. TextView

Copy codeThe Code is as follows :/**
* ReadParse (String) obtains data from the server.
* Analysis (String) parses json data
*/
Private void resultJson (){
Try {
AllData = Analysis (readParse (url ));
Iterator <HashMap <String, Object> it = allData. iterator ();
While (it. hasNext ()){
Map <String, Object> ma = it. next ();
If (Integer) ma. get ("id") = id ){
BiaoTi. setText (String) ma. get ("biaoTi "));
YuanJia. setText (String) ma. get ("yuanJia "));
XianJia. setText (String) ma. get ("xianJia "));
}
}
} Catch (JSONException e ){
E. printStackTrace ();
} Catch (Exception e ){
E. printStackTrace ();
}
}

2. ListView:

Copy codeThe Code is as follows :/**
* ListView data adaptation
*/
Private void product_data (){
List <HashMap <String, Object> lists = null;
Try {
Lists = Analysis (readParse (url); // parse json data
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
List <HashMap <String, Object> data = new ArrayList <HashMap <String, Object> ();
For (HashMap <String, Object> news: lists ){
HashMap <String, Object> item = new HashMap <String, Object> ();
Item. put ("chuXingTianShu", news. get ("chuXingTianShu "));
Item. put ("biaoTi", news. get ("biaoTi "));
Item. put ("yuanJia", news. get ("yuanJia "));
Item. put ("xianJia", news. get ("xianJia "));
Item. put ("id", news. get ("id "));

Try {
Bitmap = ImageService. getImage (news. get ("logo"). toString (); // obtain the image from the server
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
If (bitmap = null ){
Log. I ("bitmap", "" + bitmap );
Toast. makeText (TravelLine. this, "image loading error", Toast. LENGTH_SHORT)
. Show (); // display the image number
}
Item. put ("logo", bitmap );
Data. add (item );
}
ListItemAdapter = new MySimpleAdapter1 (TravelLine. this, data, R. layout. a_travelline_item,
// Subitem of the dynamic array and ImageItem
New String [] {"logo", "biaoTi ",
"XianJia", "yuanJia", "chuXingTianShu "},
// An ImageView in the XML file of ImageItem, two TextView IDS
New int [] {R. id. trl_ItemImage, R. id. trl_ItemTitle,
R. id. trl_ItemContent, R. id. trl_ItemMoney,
R. id. trl_Itemtoday });
Listview. setAdapter (listItemAdapter );
// Add and click
Listview. setOnItemClickListener (new OnItemClickListener (){
Public void onItemClick (AdapterView <?> Arg0, View arg1, int arg2,
Long arg3 ){
Login_publicchannel_trl_sub (arg2 );
}
});
}

Rewrite the adapter for images

Copy codeThe Code is as follows: package com. nuoter. adapterUntil;

Import java. util. HashMap;
Import java. util. List;

Import android. content. Context;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. graphics. Paint;
Import android.net. Uri;
Import android. view. LayoutInflater;
Import android. view. View;
Import android. view. ViewGroup;
Import android. widget. BaseAdapter;
Import android. widget. ImageView;
Import android. widget. LinearLayout;
Import android. widget. TextView;

Public class MySimpleAdapter1 extends BaseAdapter {
Private LayoutInflater mInflater;
Private List <HashMap <String, Object> list;
Private int layoutID;
Private String flag [];
Private int ItemIDs [];
Public MySimpleAdapter1 (Context context, List <HashMap <String, Object> list,
Int layoutID, String flag [], int ItemIDs []) {
This. mInflater = LayoutInflater. from (context );
This. list = list;
This. layoutID = layoutID;
This. flag = flag;
This. ItemIDs = ItemIDs;
}
@ Override
Public int getCount (){
// TODO Auto-generated method stub
Return list. size ();
}
@ Override
Public Object getItem (int arg0 ){
// TODO Auto-generated method stub
Return 0;
}
@ Override
Public long getItemId (int arg0 ){
// TODO Auto-generated method stub
Return 0;
}
@ Override
Public View getView (int position, View convertView, ViewGroup parent ){
ConvertView = mInflater. inflate (layoutID, null );
// ConvertView = mInflater. inflate (layoutID, null );
For (int I = 0; I <flag. length; I ++) {// Note 1
If (convertView. findViewById (ItemIDs [I]) instanceof ImageView ){
ImageView imgView = (ImageView) convertView. findViewById (ItemIDs [I]);
ImgView. setImageBitmap (Bitmap) list. get (position ). get (flag [I]); // The key is this sentence !!!!!!!!!!!!!!!

} Else if (convertView. findViewById (ItemIDs [I]) instanceof TextView ){
TextView TV = (TextView) convertView. findViewById (ItemIDs [I]);
TV. setText (String) list. get (position). get (flag [I]);
} Else {
//... Note 2
}
}
// AddListener (convertView );
Return convertView;
}

/* Public void addListener (final View convertView ){

ImageView imgView = (ImageView) convertView. findViewById (R. id. lxs_item_image );

}*/

}

For the image acquisition, json parses the string url: "logoLunbo": http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg to get the image from the url

ImageService Tool

Copy codeThe Code is as follows: package com. nuoter. adapterUntil;

Import java. io. ByteArrayOutputStream;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. URL;

Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;

Public class ImageService {

/**
* Obtain network image data
* @ Param path: network image path
* @ Return
*/
Public static Bitmap getImage (String path) throws Exception {

/* URL url = new URL (imageUrl );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
InputStream is = conn. getInputStream ();
MBitmap = BitmapFactory. decodeStream (is );*/
Bitmap bitmap = null;
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // HTTP-based connection object
Conn. setConnectTimeout (5000 );
Conn. setRequestMethod ("GET ");
If (conn. getResponseCode () = 200 ){
InputStream inStream = conn. getInputStream ();
Bitmap = BitmapFactory. decodeStream (inStream );
}
Return bitmap;
}

/**
* Read the data in the stream and obtain json data from the url.
* @ Param inStream
* @ Return
* @ Throws Exception
*/
Public static byte [] read (InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int len = 0;
While (len = inStream. read (buffer ))! =-1 ){
OutStream. write (buffer, 0, len );
}
InStream. close ();
Return outStream. toByteArray ();
}
}

The above also writes the network data obtained from the url in the ImageService tool class for calling, because they are all the same.

Of course, you can also write a function in the Activity class to get server images (when there are not many useful functions)

Copy codeThe Code is as follows :/*

* Retrieving images from the server
* Parameter: String type
* Return value: Bitmap type

*/

Public static Bitmap getHttpBitmap (String urlpath ){
Bitmap bitmap = null;
Try {
// Generate a URL object
URL url = new URL (urlpath );
// Open the connection
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
// Conn. setConnectTimeout (6*1000 );
// Conn. setDoInput (true );
Conn. connect ();
// Obtain the data stream
InputStream inputstream = conn. getInputStream ();
Bitmap = BitmapFactory. decodeStream (inputstream );
// Close the input stream
Inputstream. close ();
// Close the connection
Conn. disconnect ();
} Catch (Exception e ){
Log. I ("MyTag", "error:" + e. toString ());
}
Return bitmap;
}

Call:

Copy codeThe Code is as follows: public ImageView pic;
.....
.....
AllData = Analysis (readParse (url ));
Iterator <HashMap <String, Object> it = allData. iterator ();
While (it. hasNext ()){
Map <String, Object> ma = it. next ();
If (Integer) ma. get ("id") = id)
{
Logo = (String) ma. get ("logo ");
Bigpic = getHttpBitmap (logo );
}
}
Pic. setImageBitmap (bigpic );

Additionally, when downloading data is slow, create a sub-thread and pass parameters:

Copy codeThe Code is as follows: new Thread (){
@ Override
Public void run (){
// Parameter list
List <NameValuePair> nameValuePairs = new ArrayList <NameValuePair> ();
NameValuePairs. add (new BasicNameValuePair ("currPage", Integer
. ToString (1 )));
NameValuePairs. add (new BasicNameValuePair ("pageSize", Integer
. ToString (5 )));
Try {
String result = doPost (nameValuePairs, POST_URL );
Message msg = handler. obtainMessage (1, 1, 1, result );
Handler. sendMessage (msg); // send a message
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}. Start ();

// Define the Handler object
Handler = new Handler (){
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case 1 :{
// Process the UI
StringBuffer strbuf = new StringBuffer ();
List <HashMap <String, Object> lists = null;
Try {
Lists = MainActivity. this
. ParseJson (msg. obj. toString ());
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
List <HashMap <String, Object> data = new ArrayList <HashMap <String, Object> ();
For (HashMap <String, Object> news: lists ){
HashMap <String, Object> item = new HashMap <String, Object> ();
Item. put ("id", news. get ("id "));
Item. put ("ItemText0", news. get ("name "));

Try {
Bitmap = ImageService. getImage (news. get ("logo"). toString ());
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
If (bitmap = null ){
Log. I ("bitmap", "" + bitmap );
Toast. makeText (MainActivity. this, "image loading error", Toast. LENGTH_SHORT)
. Show (); // display the image number
}
Item. put ("ItemImage", bitmap );
Data. add (item );
}

// Generate the ImageItem of the adapter <====> dynamic array elements, one-to-one correspondence between the two
MySimpleAdapter saImageItems = new MySimpleAdapter (MainActivity. this, data,
R. layout. d_travelagence_item,
New String [] {"ItemImage", "ItemText0", "ItemText1 "},
New int [] {R. id. lxs_item_image, R. id. lxs_item_text0, R. id. lxs_item_text1 });
// Add and display
Gridview. setAdapter (saImageItems );
}
Break;
Default:
Break;
}

}
};

Related Article

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.