我正在尝试通过向服务器发出请求来获取列表。为此,我正在使用asynctask来处理它。代码是这样的。即使在进行了许多online的实验后,我也会得到如下的logcat错误。
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class AndroidJSONParsingActivity extends ListActivity {
public static String url = "http://ensignweb.com/sandbox/app/comment11.php";
// JSON Node names
protected static final String TAG_PRODUCTS = "products";
protected static final String TAG_CID = "cid";
public static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Message().execute(url);
startService(new Intent(this, UpdateService.class));
Intent intent = new Intent(this,UpdateService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, pIntent);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
//Belongs to update service
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// stopService(new Intent(this, UpdateService.class));
}
class Message extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
@Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
try {
// Getting Array of Contacts
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Contacts
for(int i = products.length()-1; i >=0; i--){
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_CID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CID, cid);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
mylist.add(map);
Log.d("value", mylist.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return mylist;
}
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, result , R.layout.list_item,new String[] { TAG_NAME,}, new int[] {
R.id.name});
AndroidJSONParsingActivity.this.setListAdapter(adapter);// If Activity extends ListActivity
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
}
}
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
logcat显示此消息
01-11 11:46:34.331: E/Buffer Error(483): Error converting result java.io.IOException: Attempted read on closed stream.
01-11 11:46:34.331: E/JSON Parser(483): Error parsing data org.json.JSONException: End of input at character 0 of
01-11 11:46:34.331: W/dalvikvm(483): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-11 11:46:34.342: E/AndroidRuntime(483): FATAL EXCEPTION: AsyncTask #1
01-11 11:46:34.342: E/AndroidRuntime(483): java.lang.RuntimeException: An error occured while executing doInBackground()
01-11 11:46:34.342: E/AndroidRuntime(483): at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.lang.Thread.run(Thread.java:1096)
01-11 11:46:34.342: E/AndroidRuntime(483): Caused by: java.lang.NullPointerException
01-11 11:46:34.342: E/AndroidRuntime(483): at com.androidhive.jsonparsing.AndroidJSONParsingActivity$Message.doInBackground(AndroidJSONParsingActivity.java:95)
01-11 11:46:34.342: E/AndroidRuntime(483): at com.androidhive.jsonparsing.AndroidJSONParsingActivity$Message.doInBackground(AndroidJSONParsingActivity.java:1)
01-11 11:46:34.342: E/AndroidRuntime(483): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-11 11:46:34.342: E/AndroidRuntime(483): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-11 11:46:34.342: E/AndroidRuntime(483): ... 4 more
log.d“json string”显示如下
01-11 12:43:29.891: D/json string(629): {"success":1,"products":[{"cid":"1","name":"bernard"},{"cid":"2","name":"Vijay"},{"cid":"3","name":"vikas_admin"},{"cid":"4","name":"vikas_admin"},{"cid":"5","name":"vikas_admin"},{"cid":"6","name":"vikas_admin"},{"cid":"7","name":"Vikas B L"},{"cid":"8","name":"chanakyavikas"},{"cid":"9","name":"vikram"},{"cid":"10","name":"Vidya"},{"cid":"11","name":"bernard"},{"cid":"12","name":"Thenewone"},{"cid":"13","name":"another"},{"cid":"14","name":"1245"},{"cid":"15","name":"kljdf.d,samfas"},{"cid":"16","name":"this"},{"cid":"17","name":"l;asdkfjalskjf"},{"cid":"18","name":"just got refreshed "},{"cid":"19","name":"not working"},{"cid":"20","name":"Checking"},{"cid":"21","name":"trying again"},{"cid":"22","name":"checking after few minutes"},{"cid":"23","name":"checking after many minutes"},{"cid":"24","name":"this one after 40 mintues"},{"cid":"25","name":"Let me try it once again. Even after this, it must run"},{"cid":"26","name":"Coming to track"},{"cid":"27","name":"let me check after 40 minutes"},{"cid":"28","name":"Ok. Let me give some time"},{"cid":"29","name":"let me check after lunch"},{"cid":"30","name":"checking after more than 2 hours"},{"cid":"31","name":"Now trying without icon. Lets see how it will gonna work"},{"cid":"32","name":"mic checking"},{"cid":"33","name":"check check check"},{"cid":"34","name":"check check again"},{"cid":"35","name":"Back to work"},{"cid":"36","name":"trying long long long time after"},{"cid":"37","name":"bye byeeeeeeeeeee"},{"cid":"38","name":"how is it going"},{"cid":"39","name":"Good morning Ensign"},{"cid":"40","name":"Trying AlarmManager"},{"cid":"41","name":"alarm! alarm! alarm!"},{"cid":"42","name":"Its been more than 30minutes"},{"cid":"43","name":"Let me see in the mobile about its working"},{"cid":"44","name":"How is it going"},{"cid":"45","name":"How is it going after many hours"},{"cid":"46","name":"huga huga huga"},{"cid":"47","name":"bye bye"},{"cid":"48","name":"It is now 7.47"},{"cid":"49","name":"Good morning Ensign"},{"cid":"50","name":"Once again good morning"},{"cid":"51","name":"Inside the office"},{"cid":"52","name":"Not working again"},{"cid":"53","name":"asdlkfjalsjfdl"},{"cid":"54","name":"Trying again and again"},{"cid":"55","name":"akl;sdjf;las"},{"cid":"56","name":"alarm! alarm! alarm!"},{"cid":"57","name":"adding boot complete"},{"cid":"58","name":"We are three now"},{"cid":"59","name":"check check again again"},{"cid":"60","name":"How is working now"},{"cid":"61","name":"Date is 10\/01\/2013"},{"cid":"62","name":"Now working fine"},{"cid":"63","name":"Had a good lunch"},{"cid":"64","name":"I'm with Mr. Johan "},{"cid":"65","name":"Let me check if booting works or not."},{"cid":"66","name":"checking after rebooting"},{"cid":"67","name":"Nop! rebooting not working"}]}
答案 0 :(得分:1)
使用
dialog=ProgressDialog.show(AndroidJSONParsingActivity.this,
"Processing", "Please be patient");
而不是
dialog.show(getApplicationContext(), "Processing", "Please be patient");
显示ProgressDialog
AsyncTask
答案 1 :(得分:0)
在this
方法中使用 getApplicationContext
代替onPreExecute
来显示提醒
答案 2 :(得分:0)
堆栈跟踪表明您正在尝试从已关闭的流中读取数据。这听起来就像您在关闭流后尝试从网络上读取响应。从网上阅读Json时请仔细检查。
你也得到一个空指针。要找到这些,你应该能够在调试器中逐行完成代码(如果在for循环中使用条件断点,否则调试会很糟糕)。乍一看,我猜测这是下面一行杀了你的行
products = json.getJSONArray(TAG_PRODUCTS);
我猜这是因为如果数据无法从网络返回,那么json对象将为null。
希望这有助于让我知道更多问题