ProgressDialogとJSONファイル

よく使う使い方

ファイルダウンロードするときはAsyncTask+ProgressDialogで定型が見えた
毎回使いまわせる
晒すソースはJSONファイルをダウンロードしてきて、パースするところまで

ソース

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class JsonDownloadTask extends AsyncTask<String, Integer, JSONObject> {
  private Activity mContext = null;
  private ProgressDialog mProgress = null;

  public JsonDownloadTask(Activity context) {
    mContext = context;
  }

  @Override
  protected void onPreExecute() {
    mProgress = new ProgressDialog(mContext);
    mProgress.setTitle("downloading...");
    mProgress.setMessage("please wait.");
    mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    mProgress.setCancelable(false);
    mProgress.show();
  }

  @Override
  protected JSONObject doInBackground(String... params) {
    URL url = null;
    BufferedReader reader = null;
    JSONObject json = null;
    String line;
    StringBuffer respons = new StringBuffer();

    try {
      url = new URL(params[0]);
      reader = new BufferedReader(new InputStreamReader(url
          .openConnection().getInputStream()));
      line = reader.readLine();
      while (line != null) {
        respons.append(line);
        line = reader.readLine();
      }
      json = new JSONObject(respons.toString());
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
          return null;
        }
      }
    }

    return json;
  }

  @Override
  protected void onPostExecute(JSONObject result) {
    try {
      // resultを使ってなんでも
    } finally {
      mProgress.cancel();
    }
  }
}

注意点

  • publicなクラスにしているけど、インナークラスにした方が後々のデータ表示なんか楽だよね
  • ダウンロードした後はnullチェックしないとパースでエラーがでる
  • JSONのパースにはandroid標準のものを使ってます。他にもライブラリがあるみたいだけど、試していない。もしかしたらそっちの方が早い場合があるかも