如何从PHP返回JSON对象以从Android App读取 [英] How to return JSON Object from PHP to read from Android App

查看:84
本文介绍了如何从PHP返回JSON对象以从Android App读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的MySQL表.

我需要从android应用程序发送经销商名称并将所有匹配的行发送到该应用程序.我不知道如何设置php输出.我知道我应该使用json_encode(array('stuff'));

I need to send the dealer name from android app and send all matching rows to the app.I dont know how to set the php output.I know i should encode using json_encode(array('stuff'));

但是我不知道如何格式化数据.检查 http://www.w3schools.com/json/它显示了一个示例

But i dont know how to format the data.Been checking http://www.w3schools.com/json/ It shows an example

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

我应该使用相同的格式吗?如何从android读取?我引用

Should i use the same format?How to read this from android ?Im referring http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php

    <?php

  //$con goes here 
    $result=$conn->query("SELECT pname FROM products");
    $response["stuff"] = array();

        while($row = $result->fetch_assoc())    {

            $stuff= array();

            /* ADD THE TABLE COLUMNS TO THE JSON OBJECT CONTENTS */
            $stuff["pname"] = $row['pname'];
            array_push($response["stuff"], $stuff);

            // $response[] = $row;
        }
        // success
        $response["success"] = 1;
        echo(json_encode($response));


    /* CLOSE THE CONNECTION */
    mysqli_close($conn );
    ?>

JAVA代码:

package com.example.testing;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

class testing extends AsyncTask<Void, Void, Void>   {
    JSONParser jParser; 
    String URL_TO_PHP = "http://coolsite.com/dashboard/test.php";
    String TAG_SUCCESS = "success";
    String TAG_STUFF = "stuff";

    protected Void doInBackground(Void... args) {

        /* Building Parameters */
        List <NameValuePair> params = new ArrayList<NameValuePair>();

        /* getting JSON string from URL */
        JSONObject json = jParser.makeHttpRequest(URL_TO_PHP, "GET", params);

        try {
            /* Checking for SUCCESS TAG */
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                JSONArray JAStuff = json.getJSONArray(TAG_STUFF);

                /** CHECK THE NUMBER OF RECORDS **/
                int intStuff = JAStuff.length();

                if (intStuff != 0)  {

                    for (int i = 0; i < JAStuff.length(); i++) {
                        JSONObject JOStuff = JAStuff.getJSONObject(i);
                        Log.e("ALL THE STUFF", JOStuff.toString());

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
} 

主要活动

Main activity

package com.example.testing;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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);

    }
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
          new testing().execute();
            break;
        default:
            break;
        }

    }


}

清单

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

PHP中的JSON响应

JSON Response in PHP

{"stuff":[{"pname":"Advocates"},{"pname":"Notaries"},{"pname":"Agriculture \/ Fertilizer"},{"pname":"Airconditioners"},{"pname":"Animation"},{"pname":"Airline Companies"},{"pname":"Aluminium Fabricators"},{"pname":"Amusement Parks"},{"pname":"Pets shop"},{"pname":"Association \/ Societies"},{"pname":"Astrology"},{"pname":"Attestation Service"},{"pname":"Auditorium"},{"pname":"Automobiles Accessories"},{"pname":"Automobile Dealers"},{"pname":"Ayurveda"},{"pname":"Gifts Articles"},{"pname":"Bags"},{"pname":"Batteries"},{"pname":"Bearings"},{"pname":"Beauty Parlours \/ Spa"},{"pname":"Magazine Dealers"},{"pname":"Building Contractors"},{"pname":"Building Materials"},{"pname":"Cameras"},{"pname":"Cast Iron Products"},{"pname":"Home Delivery"},{"pname":"Cements Wholesale \/ Retail"},{"pname":"Chemicals"},{"pname":"Contractors"},{"pname":"Consultants"},{"pname":"Parcel Services"},{"pname":"Crockery"},{"pname":"Dental Clinics"},{"pname":"Cyber Parks"},{"pname":"Dance School\/Costumes"},{"pname":"Diagnostics Labs& X-Rays"},{"pname":"Distance Education"},{"pname":"Driving Schools"},{"pname":"Dry Cleaners"},{"pname":"DTH Services"},{"pname":"DTP Centers"},{"pname":"Electrical Contractors \/ Services"},{"pname":"Electronics Equipment \/ Servicing"},{"pname":"Coaching Centre"},{"pname":"Event Management"},{"pname":"Fancy \/ Stationery"},{"pname":"Pooja stores"},{"pname":"Food Products"},{"pname":"Foot Wear"},{"pname":"Foreign Exchange"},{"pname":"Furniture shop"},{"pname":"Granites \/ Marbles"},{"pname":"Hospitals \/ Clinics"},{"pname":"Computer Accessories"},{"pname":"Kitchen Cabinets"},{"pname":"Library"},{"pname":"Lights \/ Fittings"},{"pname":"Mobile Phone Accesseries"},{"pname":"Machinery \/ Tools"},{"pname":"Timber Manufacturer"},{"pname":"Real Estate Agents"},{"pname":"Security Services"},{"pname":"Solar Products"},{"pname":"Health & Fitness"},{"pname":"Travel Agencies"},{"pname":"Used Car \/ Bikes"},{"pname":"Waste Management"},{"pname":"Watches & Clocks"},{"pname":"Handicrafts"},{"pname":"Doors & Windows"}],"success":1}

推荐答案

由于您发布的内容中没有提及有效的PHP文件,因此出于完整性考虑,我将其包含在内.这可能是一篇很长( long )的帖子....

Since you post does not mention a working PHP file, I will include it for the sake of completeness. This could be a long (long) post....

那么,首先.这是一个PHP文件的示例,该文件以名称 my_test.php 存储在以下位置:c:\wamp\www\some_folder_name\my_test.php(请参阅代码的编辑历史记录)

So, first. This is an example of a PHP file that is stored with the name my_test.php in at this location: c:\wamp\www\some_folder_name\my_test.php (Please see the edit history for the code)

现在,让我解释一下此PHP的重要部分.这些参数应配置为使用您的设置:

Now, let me explain the important portions of this PHP. These parameters should be configured to use your settings:

$DB_HOST = 'YOUR_IP_ADDRESS';
$DB_UNAME = 'MYSQL_USERNAME';
$DB_PWD = 'MYSQL_USER'S_PASSWORD';
$DB_DATABASE = 'DATABASE_NAME';

IP地址应为localhost或托管MySQL数据库的计算机的IP地址.最好是一个IP地址,以便您可以在物理设备上进行测试.使用 localhost 只能在虚拟设备上使用.

The IP Address should be either localhost or the IP address of the computer hosting the MySQL database. Preferably an IP address so you can test on physical devices. using localhost would work only on Virtual Devices.

下一步是将这些列添加到一个数组中,该数组将在JSON响应中构造一条记录( row ).看看这一行,例如:

Next up is adding the columns to an array that will construct a single record (row) in the JSON response. Take a look at this line for example:

$stuff["id"] = $row['id'];

$stuff["id"]基本上将成为结果JSON对象中的 tag ,而$row['id']表示数据库表中的列名.因此,$row["...."]必须与DB表中的列名相同.虽然$stuff["...."]几乎可以是任何东西.只要对您有意义.

The $stuff["id"] will basically become the tag in the resulting JSON Object whereas the $row['id'] is what indicates the column name from your DB's table. So the $row["...."] has to be identical to the column names in the DB table. While the $stuff["...."] can be just about anything. As long as it makes sense to you.

此行echo(json_encode($response));转换响应转换为JSON格式.

This line echo(json_encode($response)); will convert the response into a JSON format.

现在让我们看一下Java代码.首先,这是一个类,可以帮助您解析结果.它是从网站上的教程中删除的(我不记得是哪个).只需将以下代码复制粘贴到Java类中即可.无需更改此文件中的任何内容.请认真阅读它,以了解其工作原理.我将其命名为 JSONParser (请查看代码的编辑历史记录):

Now lets look at the Java code. First up in this is a class that will help you parse through the result. It was taken off a tutorial off a website (I don't remember which). Just copy an paste the following code in a Java class. No need to change anything in this file. Do give it a good read to understand how it works. I have it named JSONParser (Please see the edit history for the code):

最后,如何实际获得结果JSON并将其解析为Activity/Fragment.

Finally, how would to actually get the resulting JSON and parse it in an Activity / Fragment.

我解析AsyncTask中的数据,考虑到您将要执行网络操作,这仍然是必需的. (请查看代码的修改历史记录)

I parse the data in an AsyncTask, which is required anyway considering you will be performing a network operation. (Please see the edit history for the code)

此Java中的注意点:

  1. String URL_TO_PHP = "http://IP_ADDRESS/some_folder_name/my_test.php";必须具有IP地址,例如 192.168.0.x ,或者如果您正在虚拟设备上进行测试,则该地址应为 10.0.2.2 >.较早的版本( 192 .. )在模拟器上不起作用,而较晚的版本( 10.0 ... )在物理设备上不起作用.
  2. 在此:String TAG_STUFF = "stuff";中,"stuff"与此相对应,来自PHP文件:$response["stuff"] = array();. TAG_STUFF基本上应该使用$response["stuff"]中的内容.
  1. This String URL_TO_PHP = "http://IP_ADDRESS/some_folder_name/my_test.php"; needs to have either an IP address such as 192.168.0.x or if you are testing on a virtual device, it should be 10.0.2.2. The earlier (192..) won't work on an emulator and the later (10.0...) won't work on a physical device.
  2. In this: String TAG_STUFF = "stuff";, the "stuff" corresponds with this from the PHP file: $response["stuff"] = array();. The TAG_STUFF should basically use whats in $response["stuff"].

希望以上所有都是有道理的.如果您需要帮助,请发表评论. ;-)

Hope all the above makes sense. Comment if you need help. ;-)

使用工作解决方案进行了更新:

这确实很奇怪.但是,我有一个可行的解决方案.使用OP的代码时,应用程序确实崩溃了.由于没有足够的时间测试崩溃的原因,因此我直接发布了一个解决方案.

This is very weird indeed. But, I have a working solution. When using the OP's code, the application indeed crashes. For lack of time to test why it crashes, I am instead posting a solution directly.

首先,不要将testing保留为独立类,而应将其作为内部类创建回MainActivity中.

First, instead of keeping testing as an independent class, create it as an inner class back in the MainActivity.

class testing extends AsyncTask<Void, Void, Void>   {
....
}

第二,相对于onPreExecute()之前的当前声明,全局声明变量( jParserURL_TO_PHP).为清楚起见,请参见下面的完整解决方案...

Second, declare the variables globally (the jParser, URL_TO_PHP, etc), as against the current declarations before the onPreExecute(). See the complete solution below for clarity...

public class MainActivity extends Activity {

    JSONParser jParser;
    String URL_TO_PHP = "http://testbox.site50.net/test.php";
    String TAG_SUCCESS = "success";
    String TAG_STUFF = "stuff";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    ....

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                new testing().execute();
                break;
            default:
                break;
        }

    }

    private class testing extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... args) {

            /* Building Parameters */
            List<NameValuePair> params = new ArrayList<>();

            /* getting JSON string from URL */
            JSONObject json = jParser.makeHttpRequest(URL_TO_PHP, "GET", params);

            try {
                /* Checking for SUCCESS TAG */
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    JSONArray JAStuff = json.getJSONArray(TAG_STUFF);

                    /** CHECK THE NUMBER OF RECORDS **/
                    int intStuff = JAStuff.length();

                    if (intStuff != 0) {

                        for (int i = 0; i < JAStuff.length(); i++) {
                            JSONObject JOStuff = JAStuff.getJSONObject(i);
                            Log.e("ALL THE STUFF", JOStuff.toString());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
}

在进行测试时,我还对结果进行了抓屏.这里是:

While testing, I also took a screengrab of the results. Here it is:

同样,由于目前我的身体有些瘦弱,所以我将无法找出导致OP代码崩溃的真正原因.但这足以引起人们的兴趣.

Again, because I am stretched a little thin at the moment, I won't be able to go find out what really is causing the crash in the OP's code. But it's intriguing enough to find out..

这篇关于如何从PHP返回JSON对象以从Android App读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆