package com.andyidea.tabdemo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class pro_ans extends Activity { Button btn_more; TableLayout table; String response; int id; String pro; String name; String time; Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 0x123) { response = response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1); response="{objects:["+response+"]}"; try { JSONObject obj = new JSONObject(response); JSONArray jsonArray = obj.getJSONArray("objects"); for (int i = 0; i < jsonArray.length(); ++i) { JSONObject jsonObj = (JSONObject) jsonArray.get(i); id = jsonObj.getInt("pro_id"); pro = jsonObj.getString("pro_desc"); name = jsonObj.getString("name"); time = jsonObj.getString("time"); addRow(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pro_ans); table = (TableLayout) findViewById(R.id.table); btn_more = (Button) findViewById(R.id.more); btn_more.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub read(); } }); } private void addRow() { TableRow tableRow = new TableRow(this); TextView tv_id = new TextView(this); TextView tv_pro = new TextView(this); TextView tv_name = new TextView(this); TextView tv_time = new TextView(this); tv_id.setText(" " + id); tv_pro.setText(pro); tv_name.setText(name); tv_time.setText(time); tableRow.addView(tv_id); tableRow.addView(tv_pro); tableRow.addView(tv_name); tableRow.addView(tv_time); table.addView(tableRow, 1, new TableLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } public void read() { new Thread() { @Override public void run() // 在这个线程里只能写这两句话!不明觉厉! { response = GetPostUtil.sendGet( "http://222.249.250.113/Lyn/get_data/get_problem.php", ""); // 发送消息通知UI线程更新UI组件 handler.sendEmptyMessage(0x123); } }.start(); } }
不知为什么从服务器获取的Json串没了 [ ]
于是又加上了这句:
response = response.substring(response.indexOf("{"),
response.lastIndexOf("}") + 1);
response="{objects:["+response+"]}";
这有两个作用:
一、加objects {} 头,方便解析json数组
二、加 [ ]
单步调试是个好东西
http://xys289187120.blog.51cto.com/3361352/657169
浙公网安备 33010602011771号