在Android屏幕上打印JSON响应

时间:2012-07-11 16:25:07

标签: php android json api

我的Android模拟器暂时连接到我的本地计算机。它与PHP联系并发布要运行的IP地址。然后它回应了JSON结果。我想打印结果,但无法让Android屏幕改变。

这是我的活动:

public class MainActivity extends Activity implements OnClickListener {

EditText ipAddress;
Button bSearch;

String IP;

HttpClient httpclient;

HttpPost httppost;

ArrayList<NameValuePair> nameValuePairs;

HttpResponse response;
HttpEntity entity;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initialize();
    }

private void initialize(){
    ipAddress = (EditText) findViewById(R.id.IPaddress);
    bSearch = (Button) findViewById(R.id.searchBtn);

    bSearch.setOnClickListener((OnClickListener) this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub

    httpclient = new DefaultHttpClient();

    httppost = new HttpPost("http://127.0.0.1/myfiles/WorkingVersionVJSON.php");

    IP = ipAddress.getText().toString();

    nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("ipaddress", IP));

    try{
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        response = httpclient.execute(httppost);

        if(response.getStatusLine().getStatusCode()==200){

            entity = response.getEntity();

            if(entity != null){

                InputStream instream = entity.getContent();

                JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                String rIP = jsonResponse.getString("ipaddress");

            }
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

 private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

和PHP

<?php



 require("IPQFunctionworkingversionV7.php");
$ipaddress = $_POST["ipaddress"];

$results = array();

$results = getScore($ipaddress);
echo json_encode($results);
?>

当我在浏览器中运行并使用html发布它时,PHP正常工作。我假设该行

nameValuePairs.add(new BasicNameValuePair("ipaddress", IP));

以相同的方式发布到php,因为IP应该是在android上的文本框中输入的内容,它与PHP中的POST匹配。

活动编译并在模拟器上,因此我假设连接成功。我只需要以一种可以让它显示在屏幕上的方式解析JSON响应。一旦我有了,我将在布局上工作。

1 个答案:

答案 0 :(得分:1)

此外,onClick中的代码确实需要放在AsyncTask中。从UI线程调用OnClick。如果您花费太长时间进行网络通话(这是不确定的长度),Android会向您的用户发布该应用没有响应的情况。

要在屏幕上获取字符串,您的布局需要定义一个TextView,您可以使用findViewById并调用setText,或通过以编程方式对其进行充气并将其添加到显示中。