【发布时间】:2016-07-03 15:30:20
【问题描述】:
我想使用进度条显示一些 JSON 解析的进度。我从未使用过它,并在互联网上找到了一些示例。因此,我尝试实现它,但解析开始时应用程序崩溃。这是代码:
public class Parser extends Activity {
public static String w_type1 = "news";
public static String w_type2 = "events_put";
public ListView lv;
ArrayList<Widget> data = new ArrayList<Widget>();
WidgetAdapter wid_adptr = new WidgetAdapter(this, data);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parser);
lv = (ListView) this.findViewById(R.id.list);
lv.setAdapter(wid_adptr);
new ParseTask().execute();
}
private class ParseTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
public ProgressDialog dialog;
Context ctx;
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Pasring...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("http://api.pandem.pro/healthcheck/w/");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
resultJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return resultJson;
}
@Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
JSONObject dataJsonObj = null;
try {
dataJsonObj = new JSONObject(strJson);
JSONArray widgets = dataJsonObj.getJSONArray("widgets");
for (int i = 0; i < widgets.length(); i++) {
JSONObject widget = widgets.getJSONObject(i);
String wType = widget.getString("type");
if (wType.equals(w_type1) || wType.equals(w_type2)) {
String title = widget.getString("title");
String desc = widget.getString("desc");
String img_url = "";
if (widget.has("img")) {
JSONObject img = widget.getJSONObject("img");
img_url = img.getString("url");
}
data.add(new Widget(wType, title, desc, img_url));
//wid_adptr.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
dialog.dismiss();
}
}
}
如果我不使用 ProgressDialog(只是注释或删除对话框代码)应用程序可以正常工作。我该如何解决?
【问题讨论】:
-
请粘贴您的错误日志
-
在 onCreate 中创建对话框并查看上下文是否仍然为空。我认为没有错误日志很难回答您的问题。
标签: android progress-bar progressdialog