将JSON结果打印到屏幕

时间:2013-04-04 15:48:30

标签: android json http-post

我有这个HTTP / JSON代码应该从数据库中检索数据但是如何将其打印到屏幕上。如果您需要任何额外的代码,请告诉我。感谢

String result = "";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name","Badminton"));

//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}
catch(Exception e1){
Log.e("log_tag", "Error in http connection "+e1.toString());
}

//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

is.close();
result=sb.toString();
}

catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}

//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","type: "+json_data.getInt("id"));
}
}

catch(Exception e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}

那么我如何将从PHP文件中收到的数据打印到屏幕上,稍后我会做更多的事情

2 个答案:

答案 0 :(得分:1)

如果您只是想看一眼JSON,如果它足够小就可以给它干杯..

Toast.makeText(context, text, Toast.LENGTH_LONG).show();

如果你想看到整个json,可以把它放到TextView中,并使用JSON对象的toString方法来打印它。

答案 1 :(得分:0)

如果您想快速将其显示给用户,可以使用Toast。有关Toasts的更多信息,请访问here

Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGH_SHORT).show();

如果您想在特定视图中显示它,例如屏幕上显示TextView,您需要找到该视图,并设置您想要显示的文字。

TextView v = (TextView) findViewById(R.id.where_im_displaying_text);
v.setText(text);

如果您正在尝试做其他事情,请告诉我们,以便我们提供帮助。