st_dec st_dec - 1 year ago 136
Android Question

How to use ProgressDialog to show JSON parsing progress?

I want to show progress of some JSON parsing using with progress bar. I've never used it and found some examples in the Internet. So, I try to realize it but application crashes when parsing starts. Here is code:

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);

protected void onCreate(Bundle savedInstanceState) {

lv = (ListView) this.findViewById(;
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);

protected String doInBackground(Void... params) {
try {
URL url = new URL("");

urlConnection = (HttpURLConnection) url.openConnection();

InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();

reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null) {

resultJson = buffer.toString();

} catch (Exception e) {
return resultJson;

protected void onPostExecute(String 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));

} catch (JSONException e) {


If i don't use ProgressDialog (just comment or delete dialog code) application works correctly. How can I fix it?

Answer Source

Without any logcat it's difficult to help, but it seems that your ctx is null so

dialog = new ProgressDialog(ctx);

the dialog can't be created.

Try to add constructor to the AsyncTask and pass the context here, something like:

private class ParseTask extends AsyncTask<Void, Void, String> {
    public ParseTask(Context ctx) {
        this.ctx = ctx;

To start the task:

new ParseTask(this).execute();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download