問題:
簡単に言えば、進行状況ダイアログは、(php を介して) 接続している MySQL データベースから入力された ListView を開くのではなく、「データをダウンロードしています」と継続的に表示されます。
これが私のコードです:
public class Main extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
List<String> cats = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cats = new ArrayList<String>();
new task().execute();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list, cats));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long id) {
int cat_id = ((int) id);
Intent itemIntent = new Intent(getApplicationContext(), Items.class);
Bundle d = new Bundle();
cat_id = cat_id +1;
d.putString("category_id", String.valueOf(cat_id));
itemIntent.putExtras(d);
startActivity(itemIntent);
}
});
}
class task extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(Main.this);
InputStream is = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Download data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
task.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
String url_select = "http://www.--.com/---/master.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String cat;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
cat = json_data.getString("category");
cats.add(cat);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Categories Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
}