使用帶進度條的asynctask的JSON解析器。什麼是正確的方法來做到這一點?使用帶進度條的asynctask的JSON解析器
我申請和適應我從TUTS讀,但是從downloadTask
這裏返回數據時,它返回null是我downloadTask任務:
private class DownloadTask extends AsyncTask<Void, Integer, Void> {
private ProgressDialog dialog;
@Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog = new ProgressDialog(ma);
this.dialog.setIndeterminate(false);
this.dialog.setMax(100);
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.setCancelable(false);
this.dialog.setTitle(R.string.updating);
this.dialog.setMessage(getString(R.string.downloading));
this.dialog.show();
// progress = 0;
}
@Override
protected String doInBackground(String... arg0) {
int count;
byte data[] = null;
url = "http://arsonicdemo.digify.com.ph/webapi/campaigns?pf=1";
try {
URL url1 = new URL(url);
URLConnection conexion = url1.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url1.openStream());
campaignObj = new JSONObject(parser(url));
populateCampaigns(campaignObj);
appClass.updateList();
data = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100/lenghtOfFile));
}
input.close();
} catch (Exception e) {
}
return new String(data);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
Toast.makeText(ma, "Update Successful", Toast.LENGTH_SHORT).show();
ma.initMarkers();
}
}
這基本上是populateCampaigns方法:
public void populateCampaigns(String url) throws JSONException {
campaignObj = new JSONObject(parser(url));
campaignData = campaignObj.getJSONObject("data");
}
最後,這裏是解析器方法:
public static String parser(String url) {
StringBuilder builder = new StringBuilder();
System.setProperty("http.keepAlive", "false");
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeout * 1000);
client = new DefaultHttpClient(httpParams);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("CAMPAIGN DOWNLOADER ERROR", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
'最後,這裏是解析器方法:'你爲什麼卡萊該方法解析器?沒有任何解析。該方法下載一些文本。可能是json文本。但解析...不。現在什麼/哪裏是空指針? – greenapps