创建一个在onCreate()之外扩展AsyncTask的类。(不仅在这种情况下)您总是需要在方法之外创建类(除了匿名内部类等某些情况,当然这又是另一个大讨论)。然后在 onCreate() 方法中创建 AsyncTask 类的对象,并使用该对象调用方法以在不同的线程中运行该任务。根据您的代码,您无法区分这些东西。在doInBackground()中,您编写代码以获取需要在不同线程上运行的数据,在onPostExecute()方法中,您获取从 doInBackground 获得的数据并更新 UI。要更新 UI,您可以使用runOnUIThread()execute()
如下所示.. 以下是根据您的要求的伪代码(未经测试)..
public class AllEventActivity extends Activity {
private ListView listView1;
private String tag = "all";
private JSONArray json;
View header;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<AllEvent> weather_data = new ArrayList<AllEvent>();
// AllEvent weather_data[] = new AllEvent[]
// {
// new AllEvent(R.drawable.a, "Soccer Field"),
// };
weather_data.add(new AllEvent(R.drawable.a, "a", "b", "c", "d", "e"));
listView1 = (ListView)findViewById(R.id.listView1); //
header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
new All_Events_DB_Connect().execute(new String[] {"all"});
}
class All_Events_DB_Connect extends AsyncTask<String, Void, JSONArray>
{
@Override
protected JSONArray doInBackground(String... arg0)
{
String tag = arg0[0];
UserFunctions u = new UserFunctions();
//JSONObject json = new JSONObject();
JSONArray json = new JSONArray();
try
{
json = u.getAllEvents(tag);
}
catch(Exception e)
{
Log.e("Error", e.getMessage());
}
return json;
}
@Override
protected void onPostExecute(JSONArray arr)
{
//returnedJson = json;
json = arr;
runOnUiThread(new Runnable() {
public void run() {
JSONObject j = new JSONObject();
for (int i = 0; i < json.length(); i++)
{
try
{
j = json.getJSONObject(i);
Toast.makeText(this, j.getString("hostName"), Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e("JSON Error", e.getMessage());
}
}
AllEventAdapter adapter = new AllEventAdapter(this,
R.layout.listview_item_row, weather_data);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
});
}
}
}