我使用AsyncTask
將數據從服務器加載到列表中,現在我想將此列表發送到主要活動。幫助我如何做到這一點 這是主要活動如何從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);
}
這是的AsyncTask
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;
}
}
我試過很多次,請給出一個解決方案
Asynctask和活動在不同的文件? –
@Vivek沒有相同的文件 –
然後有什麼需要返回,只是使參數全局,你可以在任何地方訪問 –