Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我的android应用程序未接收json对象_Php_Android_Json - Fatal编程技术网

Php 我的android应用程序未接收json对象

Php 我的android应用程序未接收json对象,php,android,json,Php,Android,Json,我一直在开发从mysql数据库检索数据的android应用程序,因此我编写了PHP脚本,从数据库中提取数据,并将结果编码到JSON,当我测试PHP脚本时,它生成了带有对象的清晰JSON数组。 在我的android应用程序中,我编写了抓取JSON数组的代码,并从中提取数据,但我在不同的试验中都失败了,然后我开始抓取错误,发现我的应用程序接收到的内容是text/html,而不是我预期的application/JSON。当我通过单击菜单>工具>开发人员工具从我的google chrome浏览器中检查我

我一直在开发从
mysql
数据库检索数据的android应用程序,因此我编写了
PHP
脚本,从数据库中提取数据,并将结果编码到
JSON
,当我测试
PHP
脚本时,它生成了带有对象的清晰
JSON
数组。 在我的android应用程序中,我编写了抓取
JSON
数组的代码,并从中提取数据,但我在不同的试验中都失败了,然后我开始抓取错误,发现我的应用程序接收到的内容是text/html,而不是我预期的application/JSON。当我通过单击菜单>工具>开发人员工具从我的google chrome浏览器中检查我的
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 !!!!!");
    }

}
}
package com.jetas.vpl;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.http.Header;
导入org.apache.http.HeaderElement;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.params.HttpClientParams;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONArray;
导入org.json.JSONObject;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.util.Log;
导入android.widget.TextView;
公共类测试扩展了活动{
@SuppressLint(“新API”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.news\u single\u post);
StrictMode.enableDefaults();
getData();
}
public void getData(){
TextView TextView=(TextView)findViewById(R.id.newsTitle);
//TextView textview2=(TextView)findViewById(R.id.content);
//setText(“你为什么这么固执”);
InputStream isr=null;
字符串结果=”;
字符串url=”http://10.0.2.2/vpl/getnews.php";
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url);
//addHeader(“接受”、“应用程序/json”);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
isr=httpEntity.getContent();
//textview2.setText(“测试通过”);
Log.d(“连接成功”,“内容类型:”+
httpResponse.getEntity().getContentType());
}捕获(例外e){
Log.d(“连接失败”,“HTTP连接错误”+
e、 toString());
setText(“连接失败”);
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
isr,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
//textview2.setText(“测试通过”);
}
isr.close();
结果=sb.toString();
//textview2.setText(“测试通过”);
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
setText(“缓冲区读取器问题”);
}
试一试{
字符串s=“嘿”;
JSONArray jArray=新JSONArray(结果);
Log.d(“解析json”,jArray.toString());
for(int i=0;i
整合我的评论:你不能在主线程上完成你的网络工作。使用asynchtask或runnable在单独的线程中执行

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

这将只解决onmainthread异常

private Handler\u 1=null;
private Runnable mRunnable_1=null;
public void getData(){
mHandler_1=新处理程序();
mRunnable_1=新的可运行(){
public void run(){
TextView TextView=(TextView)findViewById(R.id.newsTitle);
//TextView textview2=(TextView)findViewById(R.id.content);
//setText(“你为什么这么固执”);
InputStream isr=null;
字符串结果=”;
字符串url=”http://10.0.2.2/vpl/getnews.php";
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url);
//addHeader(“接受”、“应用程序/json”);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
isr=
 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();
}
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 !!!!!");
        }

    });



    }

}