解析数据时出错org.json.JSONException:Value

时间:2014-09-25 08:58:34

标签: php android json

我已经经历了许多关于这个的帖子,但似乎没有解决我的问题。在我的应用程序中,一些Android活动和一些PHP文件正在运行,但有些不是。我真的很感激任何帮助。代码与其他正在运行的代码完全相似。我为所有人使用相同的JSONparser类,但我在以下代码中得到上述错误:

从db

获取的PHP文件
<?php

/*
 * Following code will list all the animals
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

if (isset($_GET["ct"])) {
$cat = $_GET["ct"]; 

// get all animals from animals table
$result = mysql_query("SELECT *FROM animals WHERE category = $cat ") or die(mysql_error());

// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// animals node
$response["Animals"] = array();

while ($row = mysql_fetch_array($result)) {
// temp user array
$Animal = array();
$Animal ["id"] = $row["id"];
$Animal ["name"] = $row["name"];
$Animal ["category"] = $row["category"];
$Animal ["gender"] = $row["gender"];
$Animal ["breed"] = $row["breed"];
$Animal ["dob"] = $row["dob"];
$Animal ["arrival_date"] = $row["arrival_date"];
$Animal ["purpose"] = $row["purpose"];
$Animal ["description"] = $row["description"];
$Animal ["created_at"] = $row["created_at"];
$Animal ["updated_at"] = $row["updated_at"];

// push single animal into final response array
array_push($response["Animals"], $Animal );
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no animals found
$response["success"] = 0;
$response["message"] = "No animal found";

// echo no users JSON
echo json_encode($response);
}
}else {
// no animals found
$response["success"] = 0;
$response["message"] = "Not set";

// echo no users JSON
echo json_encode($response);
}
?>

和android活动..

package com.example.androidhive;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.androidhive.Medical.LoadAllHistory;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class Categories extends ListActivity {

ArrayList<HashMap<String, String>> categoryAnimals;
String Category;
TextView txtCategory;

JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_ANIMALS = "Animals";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_CATEGORY = "category";
private static final String TAG_GENDER = "gender";
private static final String TAG_BREED = "breed";
private static final String TAG_DOB = "dob";
private static final String TAG_ARRIVAL_DATE = "arrival_date";
private static final String TAG_PURPOSE = "purpose";
private static final String TAG_DESCRIPTION = "description";
private static String url_all_medical_info = "http://10.0.2.2/android_connect/get_category.php";

JSONArray Animals  = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);

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

txtCategory = (TextView)findViewById(R.id.category);

Intent i = getIntent();
Category = i.getStringExtra(TAG_CATEGORY);
txtCategory.setText(Category);

new LoadCategoryAnimals().execute();
}

/**
 * Background Async Task to Load all medical details by making HTTP Request
 * */
class LoadCategoryAnimals extends AsyncTask<String, String, String> {
/**
 * Before starting background thread Show Progress Dialog
 * */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Categories.this);
pDialog.setMessage("..getting category'...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ct", Category));

// getting JSON string from URL

JSONObject json = jsonParser.makeHttpRequest(url_all_medical_info, "GET", params);

// Check your log cat for JSON reponse
Log.d("category animal info: ", json.toString());

try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
Animals = json.getJSONArray(TAG_ANIMALS);

// looping through All Products
for (int i = 0; i < Animals.length(); i++) {
JSONObject c = Animals.getJSONObject(i);

// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String category = c.getString(TAG_CATEGORY);
String breed = c.getString(TAG_BREED);
String gender = c.getString(TAG_GENDER);
String dob = c.getString(TAG_DOB);
String arrival_date = c.getString(TAG_ARRIVAL_DATE);
String purpose = c.getString(TAG_PURPOSE);
String description = c.getString(TAG_DESCRIPTION);

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

// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_CATEGORY, category);
map.put(TAG_BREED, breed);
map.put(TAG_GENDER, gender);
map.put(TAG_DOB, dob);
map.put(TAG_ARRIVAL_DATE, arrival_date);
map.put(TAG_PURPOSE, purpose);
map.put(TAG_DESCRIPTION, description);

// adding HashList to ArrayList
categoryAnimals.add(map);

}
} else {
// no products found

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

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {


/**
 * Updating parsed JSON data into ListView
 * */
ListAdapter adapter = new SimpleAdapter(
Categories.this, categoryAnimals,
R.layout.list_item, new String[] { TAG_ID,    TAG_NAME,   TAG_CATEGORY,       TAG_GENDER},
new int[]                        { R.id.myId, R.id.myName, R.id.textCategory, R.id.textGender});
// updating listview
setListAdapter(adapter);    
}
});

}

}
}

log cat如下所示。它似乎是成功获取但它没有解析。从“成功”一行:1是我的数据库中的动物..但它没有解析。

09-25 14:09:23.766: E/JSON Parser(414): Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
09-25 14:09:23.776: D/category animal info:(414): {"success":1,"animals":[{"arrival_date":null,"id":"6","breed":"purr","category":"Cat","description":"white eyed","dob":null,"name":"Puss","gender":"female","purpose":null},{"arrival_date":"4\/5\/2014","id":"7","breed":"meew","category":"Goat","description":"good one","dob":"3\/4\/2014","name":"salsa","gender":"Female","purpose":"Slaughter"},{"arrival_date":"6\/7\/2011","id":"9","breed":"meek","category":"Horse","description":"hairly and beautiful","dob":"6\/7\/2011","name":"Tarus","gender":"Female","purpose":"Commercial"}]}
09-25 14:09:23.776: W/System.err(414): org.json.JSONException: No value for Animals
09-25 14:09:23.796: W/System.err(414):  at org.json.JSONObject.get(JSONObject.java:354)
09-25 14:09:23.796: W/System.err(414):  at org.json.JSONObject.getJSONArray(JSONObject.java:544)
09-25 14:09:23.796: W/System.err(414):  at com.example.androidhive.Categories$LoadCategoryAnimals.doInBackground(Categories.java:104)
09-25 14:09:23.796: W/System.err(414):  at com.example.androidhive.Categories$LoadCategoryAnimals.doInBackground(Categories.java:1)
09-25 14:09:23.935: W/System.err(414):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-25 14:09:23.935: W/System.err(414):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-25 14:09:23.935: W/System.err(414):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-25 14:09:23.946: W/System.err(414):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-25 14:09:23.946: W/System.err(414):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-25 14:09:23.956: W/System.err(414):  at java.lang.Thread.run(Thread.java:1019)

0 个答案:

没有答案