public class MainActivity extends Activity{
String custid, from;
Button btnPost;
String identifier;
Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPost = (Button) findViewById(R.id.testbutton);
btnPost.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
new HttpAsyncTask().execute("http://example.com/api/customer/example/");
}
});
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("identifier", person.getIdentifier());
jsonObject.accumulate("customer_id", person.getId());
jsonObject.accumulate("from", person.getFrom());
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
person = new Person();
person.setIdentifier(identifier.toString());
person.setId(custid.toString());
person.setFrom(from.toString());
return POST(urls[0], person);
}
@Override
protected void onPostExecute(String result) {
try {
JSONObject json = new JSONObject(result);
String respResult=json.getString("result");
if(respResult.equals("ok")) {
Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG).show();
}
if(respResult.equals("error")) {
String respError=json.getString("error");
Toast.makeText(getApplicationContext(), respError, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
这是我完整的MainActivity课程。
当我单击该按钮时,我得到以下JSON格式的结果
{"result":ok","keyword":[{"business_id":"1","keyword_id":"1","created_time":"2015-03-11 14:57:58","keyword":"abc"}]}
当我单击Button时,我希望循环到这个JSON数组中,只提取关键字和created_time并将其显示在ListView中。
有人能告诉我怎么做吗?
请告诉我如何通过修改代码来为此构建Listview。
谢谢。