我的Android应用程序没有收到json对象

时间:2014-03-21 10:04:36

标签: php android json

我一直在开发从mysql数据库中检索数据的android应用程序,所以我编写了PHP脚本,从我的数据库中提取数据并将结果编码为JSON,当我测试时PHP脚本生成了清晰的JSON数组,其中包含对象。 在我的Android应用程序中,我编写了抓取JSON数组的代码并从中提取数据但是我没有通过不同的试验这样做,然后我开始抓错误并发现我的应用程序收到的内容是正如我所料,text / html而不是application / json。当我通过点击菜单>工具>开发人员工具从我的谷歌浏览器浏览器检查我的PHP脚本的内容类型时,就会产生魔力,它显示内容类型是我设置的application / json。我如此坚持这个伙伴和我的最后一年项目,我甚至不知道如何摆脱这个烂摊子。

以下是显示正在接收的内容类型为text / html的日志 03-21 09:29:18.187:D /连接成功(791):内容类型:内容类型:text / html

这是我的PHP脚本

 <?php

$connection = connect();

function connect() {
$dbhost = 'localhost';
$dbuser = 'user';
$dbpassword = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpassword);
if ($con) {
    mysql_select_db('vpl') or trigger_error(mysql_error());
}
return $con;
}

$result = mysql_query("SELECT * FROM `news` WHERE 1", $connection);

$dataArray = array();
if (mysql_num_rows($result) > 0) :
while ($row = mysql_fetch_array($result)) :
    $data['newsTitle'] = $row['newsTitle'];
    $data['newsContent'] = $row['newsContent'];

    array_push($dataArray, $data);

endwhile;
endif;
mysql_close($connection);
$json = json_encode($dataArray);
header('Content-Type: application/json');
exit($json);
?>

这是我的android代码

package com.jetas.vpl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;

public class Test extends Activity {

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_single_post);
    StrictMode.enableDefaults();
    getData();
}

public void getData() {
    TextView textview = (TextView) findViewById(R.id.newsTitle);
    // TextView textview2 = (TextView) findViewById(R.id.content);
    // textview.setText("Why are you stubborn");
    InputStream isr = null;
    String result = "";
    String url = "http://10.0.2.2/vpl/getnews.php";
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        //httpGet.addHeader("Accept", "application/json");


        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        isr = httpEntity.getContent();
        // textview2.setText("Test Passed");
            Log.d("Connection success", "Content Type: " +         
            httpResponse.getEntity().getContentType());
    } catch (Exception e) {
        Log.d("Connection failed", "Error in HTTP Connection" +   
                    e.toString());
        textview.setText("Connection Failed");
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");
            // textview2.setText("Test Passed");
        }

        isr.close();
        result = sb.toString();
        // textview2.setText("Test Passed");
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
        textview.setText("Buffer reader problem");
    }

    try {

        String s = "hey";
        JSONArray jArray = new JSONArray(result);

        Log.d("Parsing json", jArray.toString());

    for (int i = 0; i < jArray.length(); i++) {
        JSONObject json = jArray.getJSONObject(1);

        Log.d("json object", json.toString());
        Log.d("news title", json.getString("newsTitle"));


        s = s + json.getString("newsTitle");
        textview.setText(s);

            //String newsTitle = json.getString("newsTitle");
            //textview.setText(newsTitle);

             s = s + "Title: " + json.getString("newsTitle") + "\n" +
             "Content: " + json.getString("newsContent") + "\n\n";
             textview.setText(s);

        }
    } catch (Exception e) {

        Log.e("log_tag", "Error Parsing Data" + e.toString());
        textview.setText("Error in Parsing Data !!!!!");
    }

}
}

3 个答案:

答案 0 :(得分:0)

整合我的评论:你不能在主线程上做你的网络东西。使用asynchtask或runnable在单独的线程中执行。

使用runnable实现(现在可以将getdata调用到onCreate()):

这只会解决onmainthread异常

 private Handler mHandler_1=null;
 private Runnable mRunnable_1=null;

 public void getData(){
 mHandler_1 = new Handler(); 
 mRunnable_1 = new Runnable() {
    public void run() { 
        TextView textview = (TextView) findViewById(R.id.newsTitle);
        // TextView textview2 = (TextView) findViewById(R.id.content);
        // textview.setText("Why are you stubborn");
        InputStream isr = null;
        String result = "";
        String url = "http://10.0.2.2/vpl/getnews.php";
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            //httpGet.addHeader("Accept", "application/json");
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            isr = httpEntity.getContent();
            // textview2.setText("Test Passed");
            Log.d("Connection success", "Content Type: " +         
                    httpResponse.getEntity().getContentType());
        } catch (Exception e) {
            Log.d("Connection failed", "Error in HTTP Connection" +   
                    e.toString());
            textview.setText("Connection Failed");
        }
        try {
            BufferedReader reader = new BufferedReader(new                                     InputStreamReader(
                    isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                // textview2.setText("Test Passed");
            }
            isr.close();
            result = sb.toString();
            // textview2.setText("Test Passed");
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            textview.setText("Buffer reader problem");
        }
        try {
            String s = "hey";
            JSONArray jArray = new JSONArray(result);
            Log.d("Parsing json", jArray.toString());
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json = jArray.getJSONObject(1);
                Log.d("json object", json.toString());
                Log.d("news title", json.getString("newsTitle"));
                s = s + json.getString("newsTitle");
                textview.setText(s);
                //String newsTitle = json.getString("newsTitle");
                //textview.setText(newsTitle);
                s = s + "Title: " + json.getString("newsTitle") + "\n" +
                        "Content: " + json.getString("newsContent") + "\n\n";
                textview.setText(s);
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error Parsing Data" + e.toString());
            textview.setText("Error in Parsing Data !!!!!");
        }
     }
    }; 
    mRunnable_1.run();
}

PS:读这个

http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php

答案 1 :(得分:0)

尝试使用AsyncTask。或者在单独的线程中运行make network调用,稍后使用runOnUIThread()方法或Use Handler在更新UI中运行。

答案 2 :(得分:0)

您下载了jar文件httplib

将jar文件放入libs文件夹

只需将getData()方法替换为代码

即可
import com.loopj.android.http.*;
    public void getData() {
        TextView textview = (TextView) findViewById(R.id.newsTitle);
        // TextView textview2 = (TextView) findViewById(R.id.content);
        // textview.setText("Why are you stubborn");

        String result = "";
        String url = "http://10.0.2.2/vpl/getnews.php";


AsyncHttpClient client = new AsyncHttpClient();
    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            System.out.println(response);
           try {

            String s = "hey";
            JSONArray jArray = new JSONArray(response);

            Log.d("Parsing json", jArray.toString());

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json = jArray.getJSONObject(1);

            Log.d("json object", json.toString());
            Log.d("news title", json.getString("newsTitle"));


            s = s + json.getString("newsTitle");
            textview.setText(s);

                //String newsTitle = json.getString("newsTitle");
                //textview.setText(newsTitle);

                 s = s + "Title: " + json.getString("newsTitle") + "\n" +
                 "Content: " + json.getString("newsContent") + "\n\n";
                 textview.setText(s);

            }
        } catch (Exception e) {

            Log.e("log_tag", "Error Parsing Data" + e.toString());
            textview.setText("Error in Parsing Data !!!!!");
        }

    });



    }

}