0
我在這行有錯誤 - > new GetHttpResponse(this).execute();無法在setOnClickListener中執行Asynctask
它好好嘗試一下有錯誤時,它被放在按鈕
我從http://www.android-examples.com/create-dynamic-listview-using-json-parsing-php-mysql/得到這個代碼,我剛纔添加的按鈕,以便它可以在更新數據庫被刷新外
public class MainActivity extends Activity {
ListView listCollege;
ProgressBar proCollageList;
Button bton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
bton = (Button) findViewById(R.id.button);
listCollege = (ListView)findViewById(R.id.listCollege);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
new GetHttpResponse(this).execute();
bton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "List is refreshed", Toast.LENGTH_SHORT).show();
new GetHttpResponse(this).execute();
}});
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
private Context context;
String result;
List<benedict.com.listviewpractice.cources> collegeList;
public GetHttpResponse(Context context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0)
{
HttpService httpService = new HttpService("http://10.0.2.2/courses.php");
try
{
httpService.ExecutePostRequest();
if(httpService.getResponseCode() == 200)
{
result = httpService.getResponse();
Log.d("Result", result);
if(result != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
JSONObject object;
JSONArray array;
benedict.com.listviewpractice.cources college;
collegeList = new ArrayList<benedict.com.listviewpractice.cources>();
for(int i=0; i<jsonArray.length(); i++)
{
college = new benedict.com.listviewpractice.cources();
object = jsonArray.getJSONObject(i);
college.cources_name = object.getString("cource_name");
college.cources_description = object.getString("cources_description");
collegeList.add(college);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpService.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
proCollageList.setVisibility(View.GONE);
listCollege.setVisibility(View.VISIBLE);
if(collegeList != null)
{
ListAdapter adapter = new ListAdapter(collegeList, context);
listCollege.setAdapter(adapter);
}
}
}
}
考慮在這兩種情況下, –