[英]Invalid JSON response from PHP?
I am trying to parse a JSON
response from my PHP
files. 我试图从我的
PHP
文件解析JSON
响应。 The first AsyncTask
returns valid results, the 2nd does not. 第一个
AsyncTask
返回有效结果,第二个不返回。 I believe the problem is in my "mysql_queries.php". 我相信问题出在我的“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);
}
});
}
}
}
The "SearchPosts" class returns the following in the Log.v
"results" String
Which is the JSON
response I'm looking for. “SearchPosts”类在
Log.v
“results” 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
}
The "LoadAllQuestions" class returns this and then crashes “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
Here are my PHP
files 这是我的
PHP
文件
questions.php questions.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 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."')";
?>
So why does the first AsyncTask
return a valid response and the 2nd one come up null
? 那么为什么第一个
AsyncTask
返回一个有效的响应,而第二个AsyncTask
返回null
?
My educated guess is that the POST
goes out of scope by the time the "LoadAllQuestions" class tries to parse the JSON
response, but I'm new to this and I don't know how to fix it. 我有根据的猜测是,在“LoadAllQuestions”类尝试解析
JSON
响应时, POST
超出了范围,但我是新手,我不知道如何修复它。
Edit 编辑
I adjusted the code from suggestions. 我从建议中调整了代码。 I am receiving the proper
JSON
response but I am now receiving this in my logcat
. 我收到了正确的
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
<?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>
You use a GET request in your Android app, but you try to get POST data in your PHP code. 您在Android应用中使用GET请求,但尝试在PHP代码中获取POST数据。 I guess you should change this:
我想你应该改变这个:
jParser.makeHttpRequest(url, "GET",
params);
To this: 对此:
jParser.makeHttpRequest(url, "POST",
params);
The second AsyncTask doesn't add any parameter to the request ie company ,project and component.In addition You are not checking the existence of the params in the request and as mentioned in @koesie answer you must change the request type to POST instead of GET. 第二个AsyncTask不会向请求添加任何参数,即公司,项目和组件。此外,您没有检查请求中是否存在params,如@koesie中所述,您必须将请求类型更改为POST而不是得到。
Because You are sending GET request so the params should be available in $_GET , but the php code checks for $_POST data. 因为你发送GET请求所以params应该在$ _GET中可用,但php代码检查$ _POST数据。
Hope this would help 希望这会有所帮助
Update You must initialize questionList 更新您必须初始化questionList
questionList = ArrayList<HashMap<String, String>>();
UPDATE UPDATE
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);
Change 更改
jParser.makeHttpRequest(url, "GET",
params);
to 至
jParser.makeHttpRequest(url, "POST",
params);
then BEFORE that line, after your ArrayList initialization, add these values to the array, I'm assuming their the same desired values SearchPost uses.. 然后在那行之前 ,在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));
EDIT: Initialize the questionList afterwards. 编辑:之后初始化questionList。
questionList = ArrayList<HashMap<String, String>>();
EDIT 2: 编辑2:
Change 更改
R.id.genA_layout
to 至
R.layout.genA_layout
UPDATE UPDATE
You should make a separate xml layout file defining how each list view row should look like with two TextViews with ids R.id.answer, R.id.name. 您应该创建一个单独的xml布局文件, 定义每个列表视图行应如何使用两个带有ids R.id.answer,R.id.name的TextView。
A simple mockup may look like this: (please test, I've coded this straight from the answer box). 一个简单的模型可能如下所示:(请测试,我已经从答案框直接编码)。
MyListViewRow.xml 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>
Afterwards, change R.id.genA_layout to R.layout.MyListViewRow 然后,将R.id.genA_layout更改为R.layout.MyListViewRow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.