2

在此处输入图像描述伙计们,我正在尝试将我的 android 应用程序连接到 php 服务器并使用 json 来编码数据。我无法在应用程序上对其进行解码。请帮忙

public class JsonDemoActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
     HttpPost httppost;

        StringBuffer buffer;

        HttpResponse response;

        HttpClient httpclient;
        TextView tv;


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

        tv=(TextView) findViewById(R.id.textView1);
        Button b=(Button) findViewById(R.id.button1);
        b.setOnClickListener(this);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
         try{

             httpclient=new DefaultHttpClient();

             httppost= new HttpPost("http://10.0.2.2/jsondemo.php"); // make sure the url is correct.



             response=httpclient.execute(httppost);

             HttpEntity he=response.getEntity();

             JSONObject jo=new JSONObject(EntityUtils.toString(he));

             String message=jo.getString("message");
             String from=jo.getString("from");
             String to=jo.getString("to");

             tv.setText("Message "+message+"/n"+"from "+from+"/n"+"to "+to);



             tv.setText("Response from PHP : " + response);

         }catch(Exception e){

             System.out.println("Exception : " + e.getMessage());
                tv.setText(e.getLocalizedMessage());
                System.out.println("Response from php"+response);
         }

    }
}

这是php端代码

<?php

header('Content-Type: application/json');
$obj = new stdClass();

$obj->message="hello";
$obj->from="pratik";
$obj->to="server";

echo json_encode($obj);
?>

我收到错误无法将 json 转换为字符串。在此处输入图像描述

4

1 回答 1

0

我删除了 tv.setText("Response from PHP :" + response); 从代码。终于成功了。!!!

tv.setText("消息"+message+"/n"+"从"+from+"/n"+"到"+to); 那被 tv.setText("Response from PHP : " + response);

于 2012-04-11T10:11:51.050 回答