I am trying to parse a JSON
response from my PHP
files. The first AsyncTask
returns valid results, the 2nd does not. I believe the problem is in my "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.
{
"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
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
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
<?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
?
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.
Edit
I adjusted the code from suggestions. I am receiving the proper JSON
response but I am now receiving this in my 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>
You use a GET request in your Android app, but you try to get POST data in your PHP code. 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.
Because You are sending GET request so the params should be available in $_GET , but the php code checks for $_POST data.
Hope this would help
Update You must initialize questionList
questionList = ArrayList<HashMap<String, String>>();
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..
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 = ArrayList<HashMap<String, String>>();
EDIT 2:
Change
R.id.genA_layout
to
R.layout.genA_layout
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.
A simple mockup may look like this: (please test, I've coded this straight from the answer box).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.