public class MainActivity extends Activity {
private Button btnParse;
private ListView listResult;
String[] libAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnParse = (Button) findViewById(R.id.btn_parse);
btnParse.setOnClickListener(btnOKOnClickListener);
listResult = (ListView) findViewById(R.id.list_result);
listResult.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, getString(R.string.Address) + libAdd[position],
Toast.LENGTH_LONG).show();
}
});
}
public View.OnClickListener btnOKOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] libName = parseJSONData(getJSONData());
ArrayAdapter
MainActivity.this,
android.R.layout.simple_expandable_list_item_1,
libName);
listResult.setAdapter(listAdapter);
}
};
private JSONArray getJSONData() {
String uri = "http://mis.ndhu.edu.tw/android/json.php";
HttpGet httpget = new HttpGet(uri);
try {
HttpResponse httprspns = getHttpclient().execute(httpget);
String result = EntityUtils.toString(httprspns.getEntity(), HTTP.UTF_8);
Log.e("result", result);
JSONArray jsonarr = new JSONArray(result);
return jsonarr;
} catch (Exception e) {
return null;
}
}
private String[] parseJSONData(JSONArray dataInput) {
try {
String[] libName = new String[dataInput.length()];
String[] libAddress = new String[dataInput.length()];
for (int i=0; i<dataInput.length(); i++) {
JSONObject lib = dataInput.getJSONObject(i);
Log.e("name", lib.getString("name"));
Log.e("addr", lib.getString("addr"));
libName[i] = lib.getString("name");
libAddress[i] = lib.getString("addr");
}
libAdd = libAddress;
return libName;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
private DefaultHttpClient getHttpclient() {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
return httpclient;
}
}
註:
一、程式碼來源及教學參考此連結
二、教學中的 Open Data 來源有問題,已把顯示相同格式的資料移至他處。


沒有留言:
張貼留言