I am trying to fetch data from JSON into ListView but everytime i am getting blank page, neither getting List of Categories nor error.
我试图从JSON获取数据到ListView,但每次我得到空白页,既没有获得类别列表也没有错误。
I am new in Android, and trying to make Multi Level ListView using JSON,
我是Android的新手,并尝试使用JSON制作Multi Level ListView,
In my case i wanna achieve this using JSON only: Category > Items > Detail
在我的情况下,我想只使用JSON实现这一点:类别>项目>详细信息
but i am facing problem in very first screen, even not able to fetch Category
但我在第一个屏幕上遇到问题,甚至无法获取类别
JSON :
{
"categoryId": "1",
"categoryTitle": { "SmartPhones": [
{
"itemId": "1",
"itemTitle": "Galaxy Mega 5.8"
},
{
"itemId": "2",
"itemTitle": "Galaxy Mega 6.3"
}
]
},
"categoryId": "2",
"categoryTitle": { "Tablets": [
{
"itemId": "1",
"itemTitle": "Galaxy Note 510"
},
{
"itemId": "2",
"itemTitle": "Galaxy Note 800"
}
]}
}
Thanks @Segi to give me correct JSON format
谢谢@Segi给我正确的JSON格式
Activity Code:
public class CategoriesActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> categoriesList;
// albums JSONArray
JSONArray categories = null;
// albums JSON url
private static final String URL_CATEGORIES = "my.json"; // providing proper URL
// ALL JSON node names
private static final String TAG_ID = "categoryId";
private static final String TAG_TITLE = "categoryTitle";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(CategoriesActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
categoriesList = new ArrayList<HashMap<String, String>>();
// Loading Categories JSON in Background Thread
new LoadCategories().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* ProductListActivity will be lauched by passing category id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single category
// ProductListActivity will be launched to show products inside the category
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send category id to productlist activity to get list of products under that category
String category_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("category_id", category_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Categories by making http request
* */
class LoadCategories extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoriesActivity.this);
pDialog.setMessage("Listing Categories ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Categories JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_CATEGORIES, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Categories JSON: ", "> " + json);
try {
categories = new JSONArray(json);
if (categories != null) {
// looping through all categories
for (int i = 0; i < categories.length(); i++) {
JSONObject c = categories.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
// 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_TITLE, title);
// adding HashList to ArrayList
categoriesList.add(map);
}
}else{
Log.d("Categories: ", "null");
}
} 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 categories
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
CategoriesActivity.this, categoriesList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_TITLE }, new int[] {
R.id.category_id, R.id.category_title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Logcat:
06-15 12:21:27.124: D/dalvikvm(786): GC_FOR_ALLOC freed 68K, 8% free 2488K/2680K, paused 173ms, total 213ms
06-15 12:21:27.174: I/dalvikvm-heap(786): Grow heap (frag case) to 3.152MB for 635812-byte allocation
06-15 12:21:27.264: D/dalvikvm(786): GC_FOR_ALLOC freed 1K, 6% free 3108K/3304K, paused 89ms, total 89ms
06-15 12:21:27.354: D/dalvikvm(786): GC_CONCURRENT freed <1K, 6% free 3111K/3304K, paused 5ms+3ms, total 95ms
06-15 12:21:28.274: I/Choreographer(786): Skipped 41 frames! The application may be doing too much work on its main thread.
06-15 12:21:28.874: I/Choreographer(786): Skipped 123 frames! The application may be doing too much work on its main thread.
06-15 12:21:29.044: D/gralloc_goldfish(786): Emulator without GPU emulation detected.
06-15 12:21:29.134: D/dalvikvm(786): GC_CONCURRENT freed 19K, 4% free 3478K/3620K, paused 8ms+38ms, total 268ms
06-15 12:21:30.894: I/Choreographer(786): Skipped 51 frames! The application may be doing too much work on its main thread.
06-15 12:20:36.624: D/Categories JSON:(786): > {
06-15 12:20:36.624: D/Categories JSON:(786): "categoryId": "1",
06-15 12:20:36.624: D/Categories JSON:(786): "categoryTitle": {
06-15 12:20:36.624: D/Categories JSON:(786): "SmartPhones": [
06-15 12:20:36.624: D/Categories JSON:(786): {
06-15 12:20:36.624: D/Categories JSON:(786): "itemId": "1",
06-15 12:20:36.624: D/Categories JSON:(786): "itemTitle": "Galaxy Mega 5.8"
06-15 12:20:36.624: D/Categories JSON:(786): },
06-15 12:20:36.624: D/Categories JSON:(786): {
06-15 12:20:36.624: D/Categories JSON:(786): "itemId": "2",
06-15 12:20:36.624: D/Categories JSON:(786): "itemTitle": "Galaxy Mega 6.3"
06-15 12:20:36.624: D/Categories JSON:(786): }
06-15 12:20:36.624: D/Categories JSON:(786): ]
06-15 12:20:36.624: D/Categories JSON:(786): },
06-15 12:20:36.624: D/Categories JSON:(786): "categoryId": "2",
06-15 12:20:36.624: D/Categories JSON:(786): "categoryTitle": {"Tablets": [
06-15 12:20:36.624: D/Categories JSON:(786): {
06-15 12:20:36.624: D/Categories JSON:(786): "itemId": "1",
06-15 12:20:36.624: D/Categories JSON:(786): "itemTitle": "Galaxy Note 510"
06-15 12:20:36.624: D/Categories JSON:(786): },
06-15 12:20:36.624: D/Categories JSON:(786): {
06-15 12:20:36.624: D/Categories JSON:(786): "itemId": "2",
06-15 12:20:36.624: D/Categories JSON:(786): "itemTitle": "Galaxy Note 800"
06-15 12:20:36.624: D/Categories JSON:(786): }
06-15 12:20:36.624: D/Categories JSON:(786): ]}
06-15 12:20:36.624: D/Categories JSON:(786): }
06-15 12:20:36.814: W/System.err(786): org.json.JSONException: Value {"categoryTitle":{"SmartPhones":[{"itemId":"1","itemTitle":"Galaxy Mega 5.8"},{"itemId":"2","itemTitle":"Galaxy Mega 6.3"}]},"categoryId":"2"} of type org.json.JSONObject cannot be converted to JSONArray
06-15 12:20:36.824: W/System.err(786): at org.json.JSON.typeMismatch(JSON.java:111)
06-15 12:20:36.836: W/System.err(786): at org.json.JSONArray.<init>(JSONArray.java:91)
06-15 12:20:36.836: W/System.err(786): at org.json.JSONArray.<init>(JSONArray.java:103)
06-15 12:20:36.904: W/System.err(786): at com.my.json.CategoriesActivity$LoadCategories.doInBackground(CategoriesActivity.java:135)
06-15 12:20:36.904: W/System.err(786): at com.my.json.CategoriesActivity$LoadCategories.doInBackground(CategoriesActivity.java:1)
06-15 12:20:36.914: W/System.err(786): at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-15 12:20:36.914: W/System.err(786): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-15 12:20:36.925: W/System.err(786): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-15 12:20:36.925: W/System.err(786): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-15 12:20:36.934: W/System.err(786): at java.lang.Thread.run(Thread.java:856)
06-15 12:20:45.984: D/InputEventConsistencyVerifier(786): KeyEvent: ACTION_UP but key was not down.
06-15 12:20:45.984: D/InputEventConsistencyVerifier(786): in android.view.ViewRootImpl@40de89c8
06-15 12:20:45.984: D/InputEventConsistencyVerifier(786): 0: sent at 106936000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_MENU, scanCode=229, metaState=0, flags=0x8, repeatCount=0, eventTime=106936, downTime=106820, deviceId=0, source=0x101 }
Note: Getting Blank Activity, not getting data into ListView, not getting any error
注意:获取空白活动,而不是将数据导入ListView,没有收到任何错误
6 个解决方案
#1
2
JSON is valid, but illogical, should be like this
JSON是有效的,但不合逻辑,应该是这样的
[
{
"categoryId": "1",
"categoryTitle": "SmartPhones", "SmartPhones": [
{
"itemId": "1",
"itemTitle": "Galaxy Mega 5.8"
},
{
"itemId": "2",
"itemTitle": "Galaxy Mega 6.3"
}
]
},
{
"categoryId": "1",
"categoryTitle": "Tablets", "Tablets": [
{
"itemId": "1",
"itemTitle": "Galaxy Mega 5.8"
},
{
"itemId": "2",
"itemTitle": "Galaxy Mega 6.3"
}
]
}
]
Then code will be:
然后代码将是:
if (categories != null) {
// looping through All albums
for (int i = 0; i < categories.length(); i++) {
JSONObject oneCategory = categories.getJSONObject(i);
String categoryName = oneCategory.getString(TAG_ID);
String catTitle = oneCategory.getString( TAG_TITLE );
JSONArray categoryTitle = oneCategory.getJSONArray(catTitle);
for( int i = 0 ; i < categoryTitle.length() ; i++ )
{
JSONObject item = categoryTitle.getJSONObject(i);
String id = item.getString("itemId");
String name = item.getString("itemTitle");
// 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_TITLE, name);
}
// adding HashList to ArrayList
categoriesList.add(map);
}
}else{
Log.d("Categories: ", "null");
}
#2
1
Yes, from Logcat its clear that there is problem with JSON.
是的,从Logcat明确表示JSON存在问题。
Just try the following JSON.->
只需尝试以下JSON .->
[{ "categoryId": "1", { "categoryTitle": "Tablets" , "Tablets" : [ { "itemId": "1", "itemTitle": "Galaxy Mega 5.8" }, { "itemId": "2", "itemTitle": "Galaxy Mega 6.3" } ] }, {"categoryId": "2", "categoryTitle": { "Tablets": [ { "itemId": "1", "itemTitle": "Galaxy Note 510" }, { "itemId": "2", "itemTitle": "Galaxy Note 800" } ]} }]
[{“categoryId”:“1”,{“categoryTitle”:“平板电脑”,“平板电脑”:[{“itemId”:“1”,“itemTitle”:“Galaxy Mega 5.8”},{“itemId”:“ 2“,”itemTitle“:”Galaxy Mega 6.3“}]},{”categoryId“:”2“,”categoryTitle“:{”Tablets“:[{”itemId“:”1“,”itemTitle“:”Galaxy“注释510“},{”itemId“:”2“,”itemTitle“:”Galaxy Note 800“}}}}]
I did nothing special but added some brackets to make it JSON format. If you are getting this from php, make required changes there to format it.
我没有做什么特别的,但添加了一些括号,使其成为JSON格式。如果你从php获得这个,请在那里进行必要的更改以格式化它。
NB: Here, JSON has a complex structure, so be careful on parsing.
注意:这里,JSON具有复杂的结构,因此在解析时要小心。
#3
0
"categoryTitle" : "Appetizers" : [
and
"categoryTitle" : "Mixed Platter" : [
That's incorrect. What are you trying to do?
那是不对的。你想做什么?
#4
0
Try below Json:
尝试以下Json:
{
"categoryId": "1",
"categoryTitle": {
"Appetizers": [
{
"itemId": "1",
"itemTitle": "Samosa"
},
{
"itemId": "2",
"itemTitle": "Vegetable Pakora"
}
]
},
"categoryId": "2",
"categoryTitle": {"Mixed Platter": [
{
"itemId": "1",
"itemTitle": "Veggie"
},
{
"itemId": "2",
"itemTitle": "Non Veggie"
}
]}
}
#5
0
try setting the adapter to the listview right after you exit the loop (JSON Looping)
尝试在退出循环后立即将适配器设置为listview(JSON循环)
#6
0
String json = "{'categoryId': '1', 'categoryTitle': {'Appetizers': [{'itemId': '1','itemTitle': 'Samosa'},{'itemId': '2','itemTitle': 'Vegetable Pakora'}]}},{'categoryId': '2', 'categoryTitle': {'Appetizers': [{'itemId': '1','itemTitle': 'Samosa'},{'itemId': '2','itemTitle': 'Vegetable Pakora'}]}}";
try {
json = "[" + json + "]";
JSONArray mArray = new JSONArray(json);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = new JSONObject(mArray.get(0)
.toString());
String categoryId = mJsonObject.getString("categoryId");
String categoryTitle = mJsonObject.getString("categoryTitle");
mJsonObject = new JSONObject(categoryTitle);
String mVal = mJsonObject.toString().split(":")[0].replace(
"\"", "").replace("{", "");
String Resutlt = mJsonObject.getString(mVal);
JSONArray mArray1 = new JSONArray(Resutlt);
for (int j = 0; j < mArray1.length(); j++) {
mJsonObject = mArray1.getJSONObject(j);
String itemId = mJsonObject.getString("itemId");
String itemTitle = mJsonObject.getString("itemTitle");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
#1
2
JSON is valid, but illogical, should be like this
JSON是有效的,但不合逻辑,应该是这样的
[
{
"categoryId": "1",
"categoryTitle": "SmartPhones", "SmartPhones": [
{
"itemId": "1",
"itemTitle": "Galaxy Mega 5.8"
},
{
"itemId": "2",
"itemTitle": "Galaxy Mega 6.3"
}
]
},
{
"categoryId": "1",
"categoryTitle": "Tablets", "Tablets": [
{
"itemId": "1",
"itemTitle": "Galaxy Mega 5.8"
},
{
"itemId": "2",
"itemTitle": "Galaxy Mega 6.3"
}
]
}
]
Then code will be:
然后代码将是:
if (categories != null) {
// looping through All albums
for (int i = 0; i < categories.length(); i++) {
JSONObject oneCategory = categories.getJSONObject(i);
String categoryName = oneCategory.getString(TAG_ID);
String catTitle = oneCategory.getString( TAG_TITLE );
JSONArray categoryTitle = oneCategory.getJSONArray(catTitle);
for( int i = 0 ; i < categoryTitle.length() ; i++ )
{
JSONObject item = categoryTitle.getJSONObject(i);
String id = item.getString("itemId");
String name = item.getString("itemTitle");
// 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_TITLE, name);
}
// adding HashList to ArrayList
categoriesList.add(map);
}
}else{
Log.d("Categories: ", "null");
}
#2
1
Yes, from Logcat its clear that there is problem with JSON.
是的,从Logcat明确表示JSON存在问题。
Just try the following JSON.->
只需尝试以下JSON .->
[{ "categoryId": "1", { "categoryTitle": "Tablets" , "Tablets" : [ { "itemId": "1", "itemTitle": "Galaxy Mega 5.8" }, { "itemId": "2", "itemTitle": "Galaxy Mega 6.3" } ] }, {"categoryId": "2", "categoryTitle": { "Tablets": [ { "itemId": "1", "itemTitle": "Galaxy Note 510" }, { "itemId": "2", "itemTitle": "Galaxy Note 800" } ]} }]
[{“categoryId”:“1”,{“categoryTitle”:“平板电脑”,“平板电脑”:[{“itemId”:“1”,“itemTitle”:“Galaxy Mega 5.8”},{“itemId”:“ 2“,”itemTitle“:”Galaxy Mega 6.3“}]},{”categoryId“:”2“,”categoryTitle“:{”Tablets“:[{”itemId“:”1“,”itemTitle“:”Galaxy“注释510“},{”itemId“:”2“,”itemTitle“:”Galaxy Note 800“}}}}]
I did nothing special but added some brackets to make it JSON format. If you are getting this from php, make required changes there to format it.
我没有做什么特别的,但添加了一些括号,使其成为JSON格式。如果你从php获得这个,请在那里进行必要的更改以格式化它。
NB: Here, JSON has a complex structure, so be careful on parsing.
注意:这里,JSON具有复杂的结构,因此在解析时要小心。
#3
0
"categoryTitle" : "Appetizers" : [
and
"categoryTitle" : "Mixed Platter" : [
That's incorrect. What are you trying to do?
那是不对的。你想做什么?
#4
0
Try below Json:
尝试以下Json:
{
"categoryId": "1",
"categoryTitle": {
"Appetizers": [
{
"itemId": "1",
"itemTitle": "Samosa"
},
{
"itemId": "2",
"itemTitle": "Vegetable Pakora"
}
]
},
"categoryId": "2",
"categoryTitle": {"Mixed Platter": [
{
"itemId": "1",
"itemTitle": "Veggie"
},
{
"itemId": "2",
"itemTitle": "Non Veggie"
}
]}
}
#5
0
try setting the adapter to the listview right after you exit the loop (JSON Looping)
尝试在退出循环后立即将适配器设置为listview(JSON循环)
#6
0
String json = "{'categoryId': '1', 'categoryTitle': {'Appetizers': [{'itemId': '1','itemTitle': 'Samosa'},{'itemId': '2','itemTitle': 'Vegetable Pakora'}]}},{'categoryId': '2', 'categoryTitle': {'Appetizers': [{'itemId': '1','itemTitle': 'Samosa'},{'itemId': '2','itemTitle': 'Vegetable Pakora'}]}}";
try {
json = "[" + json + "]";
JSONArray mArray = new JSONArray(json);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = new JSONObject(mArray.get(0)
.toString());
String categoryId = mJsonObject.getString("categoryId");
String categoryTitle = mJsonObject.getString("categoryTitle");
mJsonObject = new JSONObject(categoryTitle);
String mVal = mJsonObject.toString().split(":")[0].replace(
"\"", "").replace("{", "");
String Resutlt = mJsonObject.getString(mVal);
JSONArray mArray1 = new JSONArray(Resutlt);
for (int j = 0; j < mArray1.length(); j++) {
mJsonObject = mArray1.getJSONObject(j);
String itemId = mJsonObject.getString("itemId");
String itemTitle = mJsonObject.getString("itemTitle");
}
}
} catch (JSONException e) {
e.printStackTrace();
}