简体   繁体   English

我的Android应用未收到json对象

[英]My android app does not receive json object

I have been developing android application that retrieve data from mysql database so I wrote the PHP script that extract data from my database and encoded the results to JSON and when i tested the PHP script it generated clear JSON array with objects in it. 我一直在开发从mysql数据库检索数据的android应用程序,因此我编写了PHP脚本,该脚本从数据库中提取数据并将结果编码为JSON ,当我测试PHP脚本时,它会生成包含对象的清晰JSON数组。 In my android app I wrote the codes the grab JSON array and extract data from it but I failed to do so with different trials, I then started to grab errors and discovered that the content that is being received by my application is text/html and not application/json as I should expect. 在我的Android应用程序中,我编写了代码以获取JSON数组并从中提取数据,但是由于尝试不同而失败,然后我开始获取错误并发现我的应用程序接收的内容是text / html和不是我应该期望的application / json。 The magic comes when I check the content type of my PHP script from my google chrome browser by clicking Menu>tool>developer tools, it shows that the content type is application/json as I set. 当我通过单击菜单>工具>开发人员工具从我的Google chrome浏览器检查PHP脚本的内容类型时,魔术就来了,它显示内容类型是我设置的application / json。 I am so so so stuck in this mate and its my final year project, I don't even know what to do to get out of this mess. 我是如此迷恋于这个伴侣和我的最后一年项目,我什至不知道该怎么做才能摆脱困境。

Here is the log that shows that the content type being received is text/html 03-21 09:29:18.187: D/Connection success(791): Content Type: Content-Type: text/html 这是日志,显示接收到的内容类型为text / html 03-21 09:29:18.187:D /连接成功(791):内容类型:Content-Type:文本/ html

Here are my PHP script 这是我的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);
?>

here are my android codes 这是我的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 !!!!!");
    }

}
}

Integrating my comment: you cannot do your network stuff on the main thread. 整合我的评论:您无法在主线程上做网络工作。 Do it in a separate thread using asynchtask or a runnable. 使用asynchtask或runnable在单独的线程中执行。

Implementation with a runnable (now you can call getdata into onCreate()): 使用可运行的实现(现在您可以将getdata调用到onCreate()中):

this will only solve the onmainthread exception 这只会解决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: read this PS:请阅读

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

Try to use AsyncTask . 尝试使用AsyncTask Or run in make network call in separate thread and Update UI later by using runOnUIThread() method or Use Handler. 或使用单独的线程在网络调用中运行,然后使用runOnUIThread()方法或“使用处理程序”在以后更新UI。

you download the jar file httplib 您下载jar文件httplib

put the jar file into the libs folder 将jar文件放入libs文件夹

and just replace the getData() method into your code 然后将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 !!!!!");
        }

    });



    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM