douci4026 2015-01-01 21:43
浏览 91
已采纳

Android JSON解析不起作用

I am trying to get Json data from a php script to my android app using JSON, and put the values in a textview. but when I run the app, I get an empty textview. what's wrong?

Notes: I added internet permission in the manifest, and the httppost and httpresponse works fine. and when I change POST to get and run the PHP script from my web browser, the data displays fine, the problem is in the JSON.

PHP:

<?php
header('Content-type: application/json');
$hostname_localhost ="localhost";
$database_localhost ="myapp_db";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);
$roomname = $_POST['roomname'];
$query_search = "select id,c_username,c_message from chats where c_roomname = '".$roomname."' ORDER BY `id`";
$query_exec = mysql_query($query_search)  or die(mysql_error());
$final_data = array(); $i=0;
while($query_row = mysql_fetch_assoc($query_exec)) 
        { 
            $username = $query_row['c_username']; 
            $message = $query_row ['c_message']; 
            $id = $query_row ['id']; 
            $data = array('id'=>$id , 'name'=> 'username : '. $username ,'message'=>'message : '. $message); 
            $final_data[$i]=$data;
            $i++;
            print(json_encode($data)); 
        } 
        //print(json_encode($final_data));


?>

Android:

 public class ChatActivity extends Activity {

    public final static String CHATTER_NAME = "com.gowemto.gowemto.USERNAME";
    public final static String CHATTER_COLOR = "com.gowemto.gowemto.CCOLOR";
    public final static String CHATROOM_NAME = "com.gowemto.gowemto.CRNAME";
    String username;
    String ccolor;
    String ncolor;
    String crname;
    String usrname;
    String usrcolor;
    String usrmessage;
    String usrdate;
    TextView teview;
    HttpPost httppost;
    StringBuffer buffer;
     String response3;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    HttpPost httppost2;
    StringBuffer buffer2;
    HttpResponse response4;
    HttpClient httpclient2;
    List<NameValuePair> nameValuePairs2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Intent intent = getIntent();
        username = intent.getStringExtra(CHATTER_NAME);
          ccolor = intent.getStringExtra(CHATTER_COLOR);
          crname = intent.getStringExtra(CHATROOM_NAME);
          String mycolor = ccolor.trim();
          teview = (TextView) findViewById(R.id.myviewer);



           new Thread(new Runnable() {
               public void run() {
                  getchats();                           
               }
             }).start();  



        setTitle(crname);

    }




 public void getchats(){
     try{            
         httpclient2=new DefaultHttpClient();
         httppost2= new HttpPost("http://10.0.2.2/myappsite/chatdata"); // make sure the url is correct.
         //add your data
         nameValuePairs2 = new ArrayList<NameValuePair>(1);

         nameValuePairs2.add(new BasicNameValuePair("roomname",crname)); 
         httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
         //Execute HTTP Post Request

         // edited by James from coderzheaven.. from here....
         response4 = httpclient2.execute(httppost2);

         ResponseHandler<String> responseHandler2 = new BasicResponseHandler();
        final String response5 = httpclient2.execute(httppost2, responseHandler2);
                 String jsonResult = inputStreamToString(response4.getEntity().getContent()).toString();
                  JSONArray mArray = new JSONArray(jsonResult);
                 for (int i = 0; i < mArray.length(); i++) {
                     JSONObject object = mArray.getJSONObject(i);

                    usrname = object.getString("username");
                    usrmessage = object.getString("message");


                 } 

                 runOnUiThread(new Runnable() {
                     public void run() {
                         teview.setText(usrname + "
" + usrmessage);
                     }
                 });


     }catch(Exception e){


     }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chat, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        }

        catch (IOException e) {
            e.printStackTrace();
         }
        return answer;
       }
}
  • 写回答

1条回答 默认 最新

  • dongyuan1984 2015-01-02 00:30
    关注

    In php script, change

    $data = array('id'=>$id , 'name'=> 'username : '. $username ,'message'=>'message : '. $message);

    to

     $data = array('id'=>$id , 'username'=> 'username : '. $username ,'message'=>'message : '. $message); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了