我正在尝试将数据填充到listview中异步
我正在从服务器检索数据作为JSON响应
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url="http://54.218.73.244:7002/";
ListView yourListView;
List<Item> yourData = new ArrayList<Item>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourListView = (ListView) findViewById(R.id.listViewID);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//Create a JSON parser Instance ----- Used JSON parser from Android
JSONObjParser jParser=new JSONObjParser();
//Getting JSON string from URL ------ Used JSON Array from Android
JSONArray json=jParser.getJSONFromUrl(url);
List<Item> yourData = new ArrayList<Item>();
try {
for(int i=0;i<json.length();i++)
{
JSONObject c=json.getJSONObject(i);// Used JSON Object from Android
String RESTAURANT_NAME=c.getString("restaurantNAME");
yourData.add(new Item(RESTAURANT_NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
}
}
}
JSONObjParser.java
public class JSONObjParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONObjParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
登录::
08-23 20:43:59.442: W/dalvikvm(1311): threadid=6: spin on suspend #1 threadid=9 (pcf=0)
08-23 20:43:59.442: D/dalvikvm(1311): Temporarily moving tid 1320 to fg (was 0)
08-23 20:43:59.442: D/dalvikvm(1311): Temporarily raised priority on tid 1320 (10 -> 0)
08-23 20:43:59.528: W/dalvikvm(1311): threadid=6: spin on suspend resolved in 1085 msec
08-23 20:43:59.528: D/dalvikvm(1311): Restored policy of 1320 to 0
08-23 20:43:59.528: D/dalvikvm(1311): Restored priority on 1320 to 10
08-23 20:44:02.460: E/JSON Parser(1311): Error parsing data org.json.JSONException: Value {"restaurants":[{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"},{"restaurantID":4,"restaurantNAME":"Indian"}],"RestaurantTimings":[{"_id":1,"RestaurantTime":"8pm to 11pm"},{"_id":2,"RestaurantTime":"10pm to 12pm"},{"_id":3,"RestaurantTime":"11pm to 9pm"},{"_id":4,"RestaurantTime":"10pm to 5pm"}]} of type org.json.JSONObject cannot be converted to JSONArray
08-23 20:44:02.470: W/dalvikvm(1311): threadid=9: thread exiting with uncaught exception (group=0x40015560)
08-23 20:44:02.489: E/AndroidRuntime(1311): FATAL EXCEPTION: AsyncTask #1
08-23 20:44:02.489: E/AndroidRuntime(1311): java.lang.RuntimeException: An error occured while executing doInBackground()
08-23 20:44:02.489: E/AndroidRuntime(1311): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.lang.Thread.run(Thread.java:1019)
08-23 20:44:02.489: E/AndroidRuntime(1311): Caused by: java.lang.NullPointerException
08-23 20:44:02.489: E/AndroidRuntime(1311): at com.project.findmybuffet.MainActivity$ParsingAsync.doInBackground(MainActivity.java:78)
08-23 20:44:02.489: E/AndroidRuntime(1311): at com.project.findmybuffet.MainActivity$ParsingAsync.doInBackground(MainActivity.java:1)
08-23 20:44:02.489: E/AndroidRuntime(1311): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-23 20:44:02.489: E/AndroidRuntime(1311): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-23 20:44:02.489: E/AndroidRuntime(1311): ... 4 more
08-23 20:44:04.531: E/WindowManager(1311): Activity com.project.findmybuffet.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051f4e8 that was originally added here
08-23 20:44:04.531: E/WindowManager(1311): android.view.WindowLeaked: Activity com.project.findmybuffet.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051f4e8 that was originally added here
08-23 20:44:04.531: E/WindowManager(1311): at android.view.ViewRoot.<init>(ViewRoot.java:258)
08-23 20:44:04.531: E/WindowManager(1311): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-23 20:44:04.531: E/WindowManager(1311): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-23 20:44:04.531: E/WindowManager(1311): at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.Dialog.show(Dialog.java:241)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ProgressDialog.show(ProgressDialog.java:107)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ProgressDialog.show(ProgressDialog.java:95)
08-23 20:44:04.531: E/WindowManager(1311): at com.project.findmybuffet.MainActivity$ParsingAsync.onPreExecute(MainActivity.java:58)
08-23 20:44:04.531: E/WindowManager(1311): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-23 20:44:04.531: E/WindowManager(1311): at com.project.findmybuffet.MainActivity.onCreate(MainActivity.java:47)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-23 20:44:04.531: E/WindowManager(1311): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 20:44:04.531: E/WindowManager(1311): at android.os.Looper.loop(Looper.java:123)
08-23 20:44:04.531: E/WindowManager(1311): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-23 20:44:04.531: E/WindowManager(1311): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 20:44:04.531: E/WindowManager(1311): at java.lang.reflect.Method.invoke(Method.java:507)
08-23 20:44:04.531: E/WindowManager(1311): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-23 20:44:04.531: E/WindowManager(1311): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-23 20:44:04.531: E/WindowManager(1311): at dalvik.system.NativeStart.main(Native Method)
08-23 20:49:02.664: I/Process(1311): Sending signal. PID: 1311 SIG: 9
08-23 21:12:52.021: E/JSON Parser(1350): Error parsing data org.json.JSONException: Value {"restaurants":[{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"},{"restaurantID":4,"restaurantNAME":"Indian"}],"RestaurantTimings":[{"_id":1,"RestaurantTime":"8pm to 11pm"},{"_id":2,"RestaurantTime":"10pm to 12pm"},{"_id":3,"RestaurantTime":"11pm to 9pm"},{"_id":4,"RestaurantTime":"10pm to 5pm"}]} of type org.json.JSONObject cannot be converted to JSONArray
08-23 21:12:52.030: W/dalvikvm(1350): threadid=9: thread exiting with uncaught exception (group=0x40015560)
08-23 21:12:52.040: E/AndroidRuntime(1350): FATAL EXCEPTION: AsyncTask #1
08-23 21:12:52.040: E/AndroidRuntime(1350): java.lang.RuntimeException: An error occured while executing doInBackground()
08-23 21:12:52.040: E/AndroidRuntime(1350): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.lang.Thread.run(Thread.java:1019)
08-23 21:12:52.040: E/AndroidRuntime(1350): Caused by: java.lang.NullPointerException
08-23 21:12:52.040: E/AndroidRuntime(1350): at com.project.findmybuffet.MainActivity$ParsingAsync.doInBackground(MainActivity.java:78)
08-23 21:12:52.040: E/AndroidRuntime(1350): at com.project.findmybuffet.MainActivity$ParsingAsync.doInBackground(MainActivity.java:1)
08-23 21:12:52.040: E/AndroidRuntime(1350): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-23 21:12:52.040: E/AndroidRuntime(1350): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-23 21:12:52.040: E/AndroidRuntime(1350): ... 4 more
08-23 21:12:54.300: E/WindowManager(1350): Activity com.project.findmybuffet.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051f950 that was originally added here
08-23 21:12:54.300: E/WindowManager(1350): android.view.WindowLeaked: Activity com.project.findmybuffet.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051f950 that was originally added here
08-23 21:12:54.300: E/WindowManager(1350): at android.view.ViewRoot.<init>(ViewRoot.java:258)
08-23 21:12:54.300: E/WindowManager(1350): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-23 21:12:54.300: E/WindowManager(1350): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-23 21:12:54.300: E/WindowManager(1350): at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.Dialog.show(Dialog.java:241)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ProgressDialog.show(ProgressDialog.java:107)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ProgressDialog.show(ProgressDialog.java:95)
08-23 21:12:54.300: E/WindowManager(1350): at com.project.findmybuffet.MainActivity$ParsingAsync.onPreExecute(MainActivity.java:58)
08-23 21:12:54.300: E/WindowManager(1350): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-23 21:12:54.300: E/WindowManager(1350): at com.project.findmybuffet.MainActivity.onCreate(MainActivity.java:47)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-23 21:12:54.300: E/WindowManager(1350): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 21:12:54.300: E/WindowManager(1350): at android.os.Looper.loop(Looper.java:123)
08-23 21:12:54.300: E/WindowManager(1350): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-23 21:12:54.300: E/WindowManager(1350): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 21:12:54.300: E/WindowManager(1350): at java.lang.reflect.Method.invoke(Method.java:507)
08-23 21:12:54.300: E/WindowManager(1350): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-23 21:12:54.300: E/WindowManager(1350): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-23 21:12:54.300: E/WindowManager(1350): at dalvik.system.NativeStart.main(Native Method)
08-23 21:13:14.790: D/dalvikvm(1350): GC_EXTERNAL_ALLOC freed 282K, 52% free 2779K/5703K, external 2061K/2137K, paused 672ms
08-23 21:13:18.330: E/JSON Parser(1350): Error parsing data org.json.JSONException: Value {"restaurants":[{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"},{"restaurantID":4,"restaurantNAME":"Indian"}],"RestaurantTimings":[{"_id":1,"RestaurantTime":"8pm to 11pm"},{"_id":2,"RestaurantTime":"10pm to 12pm"},{"_id":3,"RestaurantTime":"11pm to 9pm"},{"_id":4,"RestaurantTime":"10pm to 5pm"}]} of type org.json.JSONObject cannot be converted to JSONArray
08-23 21:13:18.330: W/dalvikvm(1350): threadid=11: thread exiting with uncaught exception (group=0x40015560)
JSON :: http://54.218.73.244:7002/
{
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy"
},
{
"restaurantID": 3,
"restaurantNAME": "MarkBoulevard"
},
{
"restaurantID": 4,
"restaurantNAME": "Indian"
}
],
"RestaurantTimings": [
{
"_id": 1,
"RestaurantTime": "8pm to 11pm"
},
{
"_id": 2,
"RestaurantTime": "10pm to 12pm"
},
{
"_id": 3,
"RestaurantTime": "11pm to 9pm"
},
{
"_id": 4,
"RestaurantTime": "10pm to 5pm"
}
]
}
答案 0 :(得分:1)
试试这个
HttpEntity httpEntity = httpResponse.getEntity();
String _response=EntityUtils.toString(httpEntity);
Log.i("Response",_response);
JSONObject jsonObject = new JSONObject(_response);
要解析我只显示了如何解析restaurants
数组。类似地解析另一个jsonarray RestaurantTimings
。
"restaurants": [ // array of restaurants
{ // json object
"restaurantID": 1, // json string
"restaurantNAME": "CopperChimney"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy"
},
{
"restaurantID": 3,
"restaurantNAME": "MarkBoulevard"
},
{
"restaurantID": 4,
"restaurantNAME": "Indian"
}
],
try
{
JSONObject jsonObject = new JSONObject(_response);
JSONArray jarr = jsonObject.getJSONArray("restaurants");
// json array restaurants
for(int i=0;i<jarr.length();i++)
{
JSONObject jb = jarr.getJSONObject(i);
String id = jb.getString("restaurantID");
String name = jb.getString("restaurantNAME");
Toast.makeText(getApplicationContext(),name, 1000).show();
}
}
catch(Exception e)
{
}
我也看到了这个
Log.i("parsing..", ""+jsonObject.get("student").toString());
jObj = new JSONArray(jsonObject.get("student").toString());
json的学生在哪里发帖。看起来你做错了
编辑:
public class MainActivity extends Activity {
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(this);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,String,String>
{
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
if(result!=null)
{
Log.i("Reponse",result);
Toast.makeText(getApplicationContext(), result, 1000).show();
// do something
}
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String s =getData();
return s;
}
private String getData() {
String _response = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://54.218.73.244:7002/");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response =EntityUtils.toString(resEntity);
//
JSONObject jsonObject = new JSONObject(_response);
JSONArray jarr = jsonObject.getJSONArray("restaurants");
for(int i=0;i<jarr.length();i++)
{
JSONObject jb = jarr.getJSONObject(i);
String id = jb.getString("restaurantID");
String name = jb.getString("restaurantNAME");
Toast.makeText(getApplicationContext(),name, 1000).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
return _response;
}
}
}
响应
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "restaurants": [
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "restaurantID": 1,
08-23 21:44:51.455: I/Reponse(24732): "restaurantNAME": "CopperChimney"
08-23 21:44:51.455: I/Reponse(24732): },
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "restaurantID": 2,
08-23 21:44:51.455: I/Reponse(24732): "restaurantNAME": "Aroy"
08-23 21:44:51.455: I/Reponse(24732): },
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "restaurantID": 3,
08-23 21:44:51.455: I/Reponse(24732): "restaurantNAME": "MarkBoulevard"
08-23 21:44:51.455: I/Reponse(24732): },
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "restaurantID": 4,
08-23 21:44:51.455: I/Reponse(24732): "restaurantNAME": "Indian"
08-23 21:44:51.455: I/Reponse(24732): }
08-23 21:44:51.455: I/Reponse(24732): ],
08-23 21:44:51.455: I/Reponse(24732): "RestaurantTimings": [
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "_id": 1,
08-23 21:44:51.455: I/Reponse(24732): "RestaurantTime": "8pm to 11pm"
08-23 21:44:51.455: I/Reponse(24732): },
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "_id": 2,
08-23 21:44:51.455: I/Reponse(24732): "RestaurantTime": "10pm to 12pm"
08-23 21:44:51.455: I/Reponse(24732): },
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "_id": 3,
08-23 21:44:51.455: I/Reponse(24732): "RestaurantTime": "11pm to 9pm"
08-23 21:44:51.455: I/Reponse(24732): },
08-23 21:44:51.455: I/Reponse(24732): {
08-23 21:44:51.455: I/Reponse(24732): "_id": 4,
08-23 21:44:51.455: I/Reponse(24732): "RestaurantTime": "10pm to 5pm"
08-23 21:44:51.455: I/Reponse(24732): }
08-23 21:44:51.455: I/Reponse(24732): ]
08-23 21:44:51.455: I/Reponse(24732): }