1

我正在尝试解析来自我的文件的JSON响应。PHP第一个AsyncTask返回有效结果,第二个没有。我相信问题出在我的“mysql_queries.php”中。

 public class GeneralAssets extends ListFragment {
View view;
EditText cn, pn;
ActionBar ab;

private String url = "http://192.168.x.x/questions.php";
private String companyName, projectName;    

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.general_assets_questions, container,
            false);

    ab = getActivity().getActionBar();
    cn = (EditText)view.findViewById(R.id.company_input);
    pn = (EditText)view.findViewById(R.id.project_input);       

    Button load = (Button) view
            .findViewById(R.id.generalAssets_load_button_ID);
    load.setOnClickListener(new View.OnClickListener() {
        boolean large = getResources().getConfiguration()
                .isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);

        @Override
        public void onClick(View v) {               
            new LoadAllQuestions().execute();
        }
    });         

    return view;
}   

class LoadAllQuestions extends AsyncTask<String, String, String> {

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_QUESTIONS = "questions";
    private static final String TAG_NAME = "display_name";
    private static final String TAG_FIELD = "field_type";

    private ProgressDialog pDialog;     

    JSONParser jParser = new JSONParser();
    JSONArray questions = null;

    ArrayList<HashMap<String, String>> questionsList = new ArrayList<HashMap<String,String>>();

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading questions. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {


        // getting JSON string from URL
        companyName = cn.getText().toString();
        projectName = pn.getText().toString();
        String componentName = (String) ab.getSelectedTab().getText();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                3);
        nameValuePairs
                .add(new BasicNameValuePair("company", companyName));
        nameValuePairs
                .add(new BasicNameValuePair("project", projectName));
        nameValuePairs
        .add(new BasicNameValuePair("component", componentName));           

        JSONObject json = jParser.makeHttpRequest(url, "POST",
                nameValuePairs);

        // Check your log cat for JSON reponse
        Log.d("All Questions: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found: getting Array of Questions
                questions = json.getJSONArray(TAG_QUESTIONS);

                // looping through All Questions
                for (int i = 0; i < questions.length(); i++) {

                    JSONObject c = questions.getJSONObject(i);

                    // Storing each json item in variable
                    String name = c.getString(TAG_NAME);
                    String field = c.getString(TAG_FIELD);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_NAME, name);
                    map.put(TAG_FIELD, field);

                    // adding HashList to ArrayList
                    questionsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Log.v("ERROR", "No JSON for you!");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();

        // updating UI from Background Thread
        getActivity().runOnUiThread(new Runnable() {
            public void run() {

                //Updating parsed JSON data into ListView                    
                ListAdapter adapter = new SimpleAdapter(getActivity(),
                        questionsList,
                        R.id.genA_layout,
                        new String[] { TAG_FIELD, TAG_NAME },
                        new int[] { R.id.answer, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });
    }
}

}

“SearchPosts”类在Log.v“结果”中返回以下内容,String这是JSON我正在寻找的响应。

{
    "questions": [
        {
            "display_name": "Store #",
            "field_type": "Text Field",
            "option_value": ""
        },
        {
            "display_name": "Address",
            "field_type": "Text Field",
            "option_value": ""
        },
        {
            "display_name": "Type of Business",
            "field_type": "Drop Down Menu",
            "option_value": "Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther"
        },
        {
            "display_name": "Is this business good?",
            "field_type": "Radio",
            "option_value": "Yes\r\nNo"
        },
        {
            "display_name": "Are they nice people?",
            "field_type": "Check Box",
            "option_value": "Yes\r\nNo"
        }
    ],
    "success": 1
}

“LoadAllQuestions”类返回这个然后崩溃

06-02 02:24:05.909: E/json data(17350): json result <br /><b>Notice</b>:  Undefined 
index: company in <b>C:\xampp\htdocs\mysql_queries.php</b> on line <b>4</b><br /><br />
<b>Notice</b>:  Undefined index: project in <b>C:\xampp\htdocs\mysql_queries.php</b> on
line <b>5</b><br /><br /><b>Notice</b>:  Undefined index: component in 
<b>C:\xampp\htdocs\mysql_queries.php</b> on line <b>6</b><br />No results found

这是我的PHP文件

问题.php

<?php

require 'connect.php';
require 'mysql_queries.php';

 if ($query_run = mysql_query($questions_query)) {
if (mysql_num_rows($query_run) == NULL) {
    echo ('No results found');
} else {            
    $response ['questions'] = array();      
    while ($row = mysql_fetch_assoc($query_run)) {
        $info = array();
        $info['display_name'] = $row['display_name'];
        $info ['field_type'] = $row['field_type'];
        $info ['option_value'] = $row['option_value'];          

        array_push($response["questions"], $info);          
    }
    // success
    $response["success"] = 1; 
    // echoing JSON response
    echo json_encode($response);
}
} else {
$response["success"] = 0; 
$response["message"] = "No data found"; 
echo json_encode($response);
}

?>

mysql_queries

<?php
require_once 'connect.php';

$company_name = $_POST['company'];
$project_name = $_POST['project'];
$component_name = $_POST['component'];

$questions_query = "SELECT CFM.display_name, CFM.field_type, CFM.option_value
                FROM company_mast
                LEFT JOIN component_mast 
                ON company_mast.id = component_mast.company_id
                LEFT JOIN CustomField_mast CFM 
                ON CFM.Company_ID = Component_mast.Company_ID
                AND CFM.Component_ID = component_Mast.Component_ID
                WHERE component_mast.component_name =  '".$component_name."'
                AND (component_mast.project_id = '".$project_name."'
                OR company_mast.company_name =  '".$company_name."')";                  
 ?>

那么为什么第一个AsyncTask返回有效响应而第二个出现null呢?

我有根据的猜测是,POST当“LoadAllQuestions”类尝试解析响应时,超出范围JSON,但我是新手,我不知道如何解决它。

编辑
我根据建议调整了代码。我收到了正确的JSON回复,但我现在在我的logcat.

 06-02 03:16:27.539: E/json data(19020): json result {"questions": [{"display_name":"Store #","field_type":"Text Field","option_value":""},{"display_name":"Address","field_type":"Text Field","option_value":""},{"display_name":"Type of Business","field_type":"Drop Down Menu","option_value":"Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther"},{"display_name":"Is this business good?","field_type":"Radio","option_value":"Yes\r\nNo"},{"display_name":"Are they nice people?","field_type":"Check Box","option_value":"Yes\r\nNo"}],"success":1}
 06-02 03:16:27.539: D/All Questions:(19020): {"success":1,"questions":[{"option_value":"","field_type":"Text Field","display_name":"Store #"},{"option_value":"","field_type":"Text Field","display_name":"Address"},{"option_value":"Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther","field_type":"Drop Down Menu","display_name":"Type of Business"},{"option_value":"Yes\r\nNo","field_type":"Radio","display_name":"Is this business good?"},{"option_value":"Yes\r\nNo","field_type":"Check Box","display_name":"Are they nice people?"}]}

    06-02 03:35:11.069: E/json data(19250): json result {"questions":[{"display_name":"Store #","field_type":"Text Field","option_value":""},{"display_name":"Address","field_type":"Text Field","option_value":""},{"display_name":"Type of Business","field_type":"Drop Down Menu","option_value":"Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther"},{"display_name":"Is this business good?","field_type":"Radio","option_value":"Yes\r\nNo"},{"display_name":"Are they nice people?","field_type":"Check Box","option_value":"Yes\r\nNo"}],"success":1}
06-02 03:35:11.079: D/All Questions:(19250): {"success":1,"questions":[{"option_value":"","field_type":"Text Field","display_name":"Store #"},{"option_value":"","field_type":"Text Field","display_name":"Address"},{"option_value":"Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther","field_type":"Drop Down Menu","display_name":"Type of Business"},{"option_value":"Yes\r\nNo","field_type":"Radio","display_name":"Is this business good?"},{"option_value":"Yes\r\nNo","field_type":"Check Box","display_name":"Are they nice people?"}]}
06-02 03:35:11.109: D/AndroidRuntime(19250): Shutting down VM
06-02 03:35:11.109: W/dalvikvm(19250): threadid=1: thread exiting with uncaught exception (group=0x41093930)
06-02 03:35:11.129: E/AndroidRuntime(19250): FATAL EXCEPTION: main
06-02 03:35:11.129: E/AndroidRuntime(19250): android.content.res.Resources$NotFoundException: Resource ID #0x7f09009f type #0x12 is not valid
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.content.res.Resources.loadXmlResourceParser(Resources.java:2144)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.content.res.Resources.getLayout(Resources.java:853)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.LayoutInflater.inflate(LayoutInflater.java:394)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:121)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.AbsListView.obtainView(AbsListView.java:2159)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.ListView.onMeasure(ListView.java:1130)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1052)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1217)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.ScrollView.onMeasure(ScrollView.java:321)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1231)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.View.measure(View.java:15518)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.Choreographer.doFrame(Choreographer.java:532)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.os.Handler.handleCallback(Handler.java:725)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.os.Looper.loop(Looper.java:137)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at android.app.ActivityThread.main(ActivityThread.java:5041)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at java.lang.reflect.Method.invokeNative(Native Method)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at java.lang.reflect.Method.invoke(Method.java:511)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-02 03:35:11.129: E/AndroidRuntime(19250):    at dalvik.system.NativeStart.main(Native Method)

XML

    <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gen_assets"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="@drawable/twoglobe_line"
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/genA_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/loader_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:gravity="center"
            android:orientation="vertical" >

            <LinearLayout
                android:id="@+id/info_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:gravity="center"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/company_name"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:text="@string/company_name" />

                <EditText
                    android:id="@+id/company_input"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:ems="10" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/info_layout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:gravity="center"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/project_name"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:text="@string/project_name" />

                <EditText
                    android:id="@+id/project_input"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:ems="10" />
            </LinearLayout>

            <Button
                android:id="@+id/generalAssets_load_button_ID"
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/load" />

            <ListView
                android:id="@android:id/list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:drawSelectorOnTop="false" >
            </ListView>
        </LinearLayout>

        <TextView
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:visibility="gone" />

        <TextView
            android:id="@+id/answer"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:visibility="gone" />
    </LinearLayout>
    </ScrollView>
4

3 回答 3

1

您在 Android 应用程序中使用 GET 请求,但您尝试在 PHP 代码中获取 POST 数据。我想你应该改变这个:

jParser.makeHttpRequest(url, "GET",
            params);

对此:

jParser.makeHttpRequest(url, "POST",
            params);
于 2013-06-02T06:59:15.247 回答
1

第二个 AsyncTask 没有向请求添加任何参数,即公司、项目和组件。此外,您没有检查请求中是否存在参数,如@koesie 回答中所述,您必须将请求类型更改为 POST 而不是得到。

因为您正在发送 GET 请求,所以参数应该在 $_GET 中可用,但是 php 代码会检查 $_POST 数据。

希望这会有所帮助

更新 您必须初始化 questionList

questionList = ArrayList<HashMap<String, String>>();

更新

ListAdapter adapter = new SimpleAdapter(getActivity(),
                        questionsList,
                        R.layout.genA_layout,
                        new String[] { TAG_FIELD, TAG_NAME },
                        new int[] { R.id.answer, R.id.name });
                // updating listview
                setListAdapter(adapter);
于 2013-06-02T07:09:37.503 回答
1

改变

jParser.makeHttpRequest(url, "GET",
            params);

jParser.makeHttpRequest(url, "POST",
            params);

然后在该行之前,在您的 ArrayList 初始化之后,将这些值添加到数组中,我假设它们与 SearchPost 使用的相同期望值..

        String companyName = cn.getText().toString();
        String projectName = pn.getText().toString();
        String componentName = (String) ab.getSelectedTab().getText();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("company", companyName));
        params.add(new BasicNameValuePair("project", projectName));
        params.add(new BasicNameValuePair("component", componentName));

编辑: 之后初始化 questionList。

 questionList = ArrayList<HashMap<String, String>>();

编辑2:

改变

R.id.genA_layout

R.layout.genA_layout

更新

您应该创建一个单独的 xml 布局文件,定义每个列表视图行的外观,其中包含两个 ID 为 R.id.answer、R.id.name 的 TextView。

一个简单的模型可能如下所示:(请测试,我已经直接从答案框中编码)。

MyListViewRow.xml

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="vertical"> <!-- You can make orientation horizontal also -->

    <TextView
        android:id="@+id/answer"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>

   <TextView
        android:id="@+id/answer"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
</LinearLayout>

之后,将 R.id.genA_layout 更改为 R.layout.MyListViewRow

于 2013-06-02T07:27:50.093 回答