【发布时间】:2016-04-03 18:27:11
【问题描述】:
我使用AsyncTask 将数据从服务器加载到列表中,现在我想将此列表发送到主活动。帮助我如何做到这一点
这是主要活动
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx=(TextView)findViewById(R.id.textView);
ls=(ListView)findViewById(R.id.listView);
bn=(Button)findViewById(R.id.button);
new Dataload().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
这是异步任务
class Dataload extends AsyncTask<String,Void,ArrayAdapter> {
String returnString, s = "";
String name;
int quantity,price;
ArrayList<String> list = new ArrayList<String>();
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(ArrayAdapter adapter) {
ls.setAdapter(adapter);
}
@Override
protected ArrayAdapter doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("h", s));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://grclive.16mb.com/select_rum.php",
postParameters);
String result = response.toString();
try {
returnString = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
name = json_data.getString("r_name");
quantity=json_data.getInt("r_quantity");
price=json_data.getInt("r_price");
list1.add(name + " " + quantity + " L" + " " + price + " ₹");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getApplicationContext(),R.layout.textfield, list1);
return adapter;
}
}
试了很多次,求解答
【问题讨论】:
-
异步任务和活动是否在不同的文件中?
-
那么需要返回什么,只要把那个参数设为全局,你就可以在任何地方访问它
-
我试过了,但是应用崩溃了
-
什么是崩溃日志以及您在哪里尝试获取数据
-
这是因为只有在
onPostExecute中检索到数据后才需要调用此方法
标签: android android-activity android-asynctask