public class AllProductsActivity extends ListActivity {
ListView list;
TextView id;
TextView name;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.3/app/a.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TRUE = "true";
private static final String TAG_PRODUCTS = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
String pid,names,j;
String s;
// products JSONArray
JSONArray product = null;
JSONObject n = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
}
// Response from Edit Product Activity
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
id = (TextView) findViewById(R.id.pid);
name = (TextView) findViewById(R.id.name);
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
@Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONArray json = jParser.makeHttpRequest(url_all_products, "GET", params);
JSONObject jsonResponse;
Log.d("All Products: ", json.toString());
jsonResponse = new JSONObject();
try {
product = jsonResponse.getJSONArray(TAG_TRUE);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int c = jsonResponse.optInt(TAG_SUCCESS);
if(c==1)
{
j = jsonResponse.optString(TAG_PRODUCTS);
for(int i=0;i<j.length();i++){
// productsList.(json.getString(i));
pid = jsonResponse.optString(TAG_PID);
names = jsonResponse.optString(TAG_NAME);
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, pid);
map.put(TAG_NAME, names);
// adding HashList to ArrayList
productsList.add(map);
}
else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList, R.layout.list_item, new String[] { TAG_PID, TAG_NAME}, new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
PHP代码
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
$r = array();
// get all products from products table
$db = new PDO('mysql:host=localhost;dbname=androidhive;charset=utf8', 'Sidd');
$stmt = $db->query('SELECT * FROM product');
$json= array();
$json[0]= 'true';
//$r["a"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// looping through all results
// products node
// temp user array
$response["product"] = array();
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
// push single product into final response array
array_push($response["product"], $product);
// array_push($r["a"], $response);
// success
$response["success"] = 1;
$json[]= $response;
}
// echoing JSON response
echo json_encode($json);
//}
?>
错误消息
09-07 14:54:00.285: D/AbsListView(10521): Get MotionRecognitionManager
09-07 14:54:00.290: D/ProgressBar(10521): setProgress = 0
09-07 14:54:00.290: D/ProgressBar(10521): setProgress = 0, fromUser = false
09-07 14:54:00.290: D/ProgressBar(10521): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
09-07 14:54:00.310: D/AbsListView(10521): onVisibilityChanged() is called, visibility : 4
09-07 14:54:00.310: D/AbsListView(10521): unregisterIRListener() is called
09-07 14:54:00.310: D/AbsListView(10521): onVisibilityChanged() is called, visibility : 0
09-07 14:54:00.310: D/AbsListView(10521): unregisterIRListener() is called
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: left = 0
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: top = 0
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: right = 96
09-07 14:54:00.335: D/ProgressBar(10521): updateDrawableBounds: bottom = 96
09-07 14:54:00.395: D/AbsListView(10521): unregisterIRListener() is called
09-07 14:54:00.445: D/AbsListView(10521): unregisterIRListener() is called
09-07 14:54:00.520: D/All Products:(10521): ["true",{"product":[{"pid":"1","name":"sid"}],"success":1},{"product":[{"pid":"2","name":"shef"}],"success":1}]
09-07 14:54:00.520: W/System.err(10521): org.json.JSONException: No value for true
09-07 14:54:00.525: W/System.err(10521): at org.json.JSONObject.get(JSONObject.java:354)
09-07 14:54:00.525: W/System.err(10521): at org.json.JSONObject.getJSONArray(JSONObject.java:548)
09-07 14:54:00.525: W/System.err(10521): at com.example.jsontry.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:104)
09-07 14:54:00.525: W/System.err(10521): at com.example.jsontry.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
09-07 14:54:00.525: W/System.err(10521): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-07 14:54:00.525: W/System.err(10521): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-07 14:54:00.525: W/System.err(10521): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-07 14:54:00.525: W/System.err(10521): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-07 14:54:00.525: W/System.err(10521): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-07 14:54:00.525: W/System.err(10521): at java.lang.Thread.run(Thread.java:841)
09-07 14:54:00.760: D/AbsListView(10521): unregisterIRListener() is called
09-07 14:54:00.890: D/AbsListView(10521): onDetachedFromWindow
**
我无法解析数据。我的代码有什么问题?
我是Android新手,我在这里完全空白。任何帮助将不胜感激!
我在这里尝试过各种各样的事情
如果我必须从数据库中检索图像并在Android中的ListView
或自定义视图中显示它们,该怎么办?
答案 0 :(得分:0)
从JSON中删除product,success
等重复键,使用PHP代码格式化您的JSON,并使其如下所示,这有助于您轻松解析JSON。
例如:
{"product":[{"pid":"1","name":"sid"},{"pid":"2","name":"shef"}],"success":"1","value":"true"}
如果您能够像上面那样创建JSON。然后你可以使用下面的代码解析它
JSONArray productDetailsJsonArr = reader.getJSONArray("product");
for (int i = 0; i < productDetailsJsonArr.length(); i++) {
JSONObject pJsonObj = productDetailsJsonArr.getJSONObject(i);
String pid = pJsonObj.getString("pid");
String sid = pJsonObj.getString("sid");
}
String success = reader.getString("success");
String value = reader.getString("value");
答案 1 :(得分:0)
试试这个:
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$response["product"] = $product;
unset($product);
}
$response["success"] = 1;
$json[]= $response;
答案 2 :(得分:0)
您的doInBackground
代码存在问题
JSONArray json = jParser.makeHttpRequest(url_all_products, "GET", params);
在这里,您将获取json
变量中的数据,而无法使用它