First, the client gets json data from the server side
1. Use HttpUrlConnection
/**
* Get 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) ();
InputStream inStream = ();
while ((len = (data)) != -1) {
(data, 0, len);
}
();
return new String(());//By obtaining the written data
}
2. Use HttpClient
/**
* Access the database and return the JSON data string
*
* @param params Params Params Params
* @param url
* @return
* @throws Exception
*/
public static String doPost(List<NameValuePair> params, String url)
throws Exception {
String result = null;
// Get the HttpClient object
HttpClient httpClient = new DefaultHttpClient();
// Create a new HttpPost object
HttpPost httpPost = new HttpPost(url);
if (params != null) {
// Set character set
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// Set parameter entity
(entity);
}
/*// Connection timeout
().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
// Request timeout
().setParameter(CoreConnectionPNames.SO_TIMEOUT,
3000);*/
// Get the HttpResponse instance
HttpResponse httpResp = (httpPost);
// The judgment is that the request is successful
if (().getStatusCode() == 200) {
// Get the returned data
result = ((), "UTF-8");
} else {
("HttpPost", "HttpPost method request failed");
}
return result;
}
Secondly, Json data analysis:
json data: [{"id":"67","biaoTi":"G","logo":"/wserver/resources/upload/","logoLunbo":"/wserver/resources/upload/","yuanJia":"0","xianJia":"0"},{"id":"64","biaoTi":"444","logo":"/wserver/resources/upload/","logoLunbo":"http://172.16 .1.75:8080/wserver/resources/upload/","yuanJia":"0","xianJia":"0"},{"id":"62","biaoTi":"jhadasd","logo":"/wserver/resources/upload/","logoLunbo":"http://172.16.1.75:8080/wserver/resources/upload/","yuanJia":"1","xianJia":"0"}]
/**
* Analysis
*
* @throws JSONException
*/
private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr)
throws JSONException {
/********************* Analysis ************************/
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 < (); i++) {
JSONObject jsonObject = (i);
// Initialize map array object
HashMap<String, Object> map = new HashMap<String, Object>();
("logo", ("logo"));
("logoLunbo", ("logoLunbo"));
("biaoTi", ("biaoTi"));
("yuanJia", ("yuanJia"));
("xianJia", ("xianJia"));
("id", ("id"));
(map);
}
return list;
}
Last data adaptation:
1、TextView
/**
* readParse(String) gets data from the server side
* Analysis (String) parses json data
*/
private void resultJson() {
try {
allData = Analysis(readParse(url));
Iterator<HashMap<String, Object>> it = ();
while (()) {
Map<String, Object> ma = ();
if ((Integer) ("id") == id) {
((String) ("biaoTi"));
((String) ("yuanJia"));
((String) ("xianJia"));
}
}
} catch (JSONException e) {
();
} catch (Exception e) {
();
}
}
2、ListView:
/**
* ListView data adaptation
*/
private void product_data(){
List<HashMap<String, Object>> lists = null;
try {
lists = Analysis(readParse(url));// parse out json data
} catch (Exception e) {
// TODO Auto-generated catch block
();
}
List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
for(HashMap<String, Object> news : lists){
HashMap<String, Object> item = new HashMap<String, Object>();
("chuXingTianShu", ("chuXingTianShu"));
("biaoTi", ("biaoTi"));
("yuanJia", ("yuanJia"));
("xianJia", ("xianJia"));
("id", ("id"));
try {
bitmap = (("logo").toString());//The picture is obtained from the server
} catch (Exception e) {
// TODO Auto-generated catch block
();
}
if(bitmap==null){
("bitmap", ""+bitmap);
(, "Image loading error", Toast.LENGTH_SHORT)
.show(); �
}
("logo",bitmap);
(item);
}
listItemAdapter = new MySimpleAdapter1(,data,.a_travelline_item,
// Subitems corresponding to dynamic array and ImageItem
new String[] { "logo", "biaoTi",
"xianJia", "yuanJia", "chuXingTianShu"},
// One ImageView and two TextView IDs in the XML file of ImageItem
new int[] { .trl_ItemImage, .trl_ItemTitle,
.trl_ItemContent, .trl_ItemMoney,
.trl_Itemtoday});
(listItemAdapter);
//Add click
(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
login_publicchannel_trl_sub(arg2);
}
});
}
For those with pictures, rewrite the adapter
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
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[]) {
= (context);
= list;
= layoutID;
= flag;
= ItemIDs;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return ();
}
@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 = (layoutID, null);
// convertView = (layoutID, null);
for (int i = 0; i < ; i++) {//Note 1
if ((ItemIDs[i]) instanceof ImageView) {
ImageView imgView = (ImageView) (ItemIDs[i]);
((Bitmap) (position).get(flag[i]));//////////////////////////////////////// The key is this sentence!!!!!!!!!!!!!!!
}else if ((ItemIDs[i]) instanceof TextView) {
TextView tv = (TextView) (ItemIDs[i]);
((String) (position).get(flag[i]));
}else{
//...Remark 2
}
}
//addListener(convertView);
return convertView;
}
/* public void addListener(final View convertView) {
ImageView imgView = (ImageView)(.lxs_item_image);
} */
}
For the acquisition of the image, json parses the string url: "logoLunbo":/wserver/resources/upload/ Get the image from the url
ImageService tool class
package ;
import ;
import ;
import ;
import ;
import ;
import ;
public class ImageService {
/**
* Obtain data of network pictures
* @param path Network image path
* @return
*/
public static Bitmap getImage(String path) throws Exception{
/*URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) ();
InputStream is = ();
mBitmap = (is);*/
Bitmap bitmap= null;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) ();//Connect objects based on HTTP protocol
(5000);
("GET");
if(() == 200){
InputStream inStream = ();
bitmap = (inStream);
}
return bitmap;
}
/**
* Read data in the stream Get json data from 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 = (buffer)) != -1){
(buffer, 0, len);
}
();
return ();
}
}
The above also writes the acquisition of network data from the URL and calls it in the tool class ImageService because it is all the same.
Of course, you can also write a function to get server pictures in the Activity class (when it is not very useful)
/*
* Get pictures from the server
* Parameters: String type
* Return: 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)();
// (6*1000);
// (true);
();
//Get data stream
InputStream inputstream = ();
bitmap = (inputstream);
//Close the input stream
();
//Close the connection
();
} catch (Exception e) {
("MyTag", "error:"+());
}
return bitmap;
}
Called:
public ImageView pic;
.....
.....
allData=Analysis(readParse(url));
Iterator<HashMap<String, Object>> it=();
while(()){
Map<String, Object> ma=();
if((Integer)("id")==id)
{
logo=(String) ("logo");
bigpic=getHttpBitmap(logo);
}
}
(bigpic);
Also, when downloading data is very slow, create a child thread and pass parameters:
new Thread() {
@Override
public void run() {
// Parameter list
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
(new BasicNameValuePair("currPage", Integer
.toString(1)));
(new BasicNameValuePair("pageSize", Integer
.toString(5)));
try {
String result = doPost(nameValuePairs, POST_URL);
Message msg = (1, 1, 1, result);
(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
();
}
}
}.start();
// Define Handler object
handler = new Handler() {
public void handleMessage(Message msg) {
switch () {
case 1:{
// Process UI
StringBuffer strbuf = new StringBuffer();
List<HashMap<String, Object>> lists = null;
try {
lists =
.parseJson(());
} catch (Exception e) {
// TODO Auto-generated catch block
();
}
List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
for(HashMap<String, Object> news : lists){
HashMap<String, Object> item = new HashMap<String, Object>();
("id", ("id"));
("ItemText0", ("name"));
try {
bitmap = (("logo").toString());
} catch (Exception e) {
// TODO Auto-generated catch block
();
}
if(bitmap==null){
("bitmap", ""+bitmap);
(, "Image loading error", Toast.LENGTH_SHORT)
.show(); �
}
("ItemImage",bitmap);
(item);
}
//The ImageItem of the generator <====> element of the dynamic array, the two correspond one by one
MySimpleAdapter saImageItems = new MySimpleAdapter(, data,
.d_travelagence_item,
new String[] {"ItemImage", "ItemText0", "ItemText1"},
new int[] {.lxs_item_image, .lxs_item_text0, .lxs_item_text1});
//Add and display
(saImageItems);
}
break;
default:
break;
}
}
};