gpt4 book ai didi

java - 异步任务中的多个操作 (Android)

转载 作者:行者123 更新时间:2023-12-02 12:18:38 24 4
gpt4 key购买 nike

异步任务中是否可以有多个httpclient?在我下面的代码中..它检索用户的信息,然后将其显示到一个新 Activity 中..但是我还想在执行 ProfileAsync 时获取关注者的数量和用户的关注者..我有单独的 php 文件检索用户信息以及关注者和关注者的数量..

class ProfileAsync extends AsyncTask<String, String, String>{

private Dialog loadingDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(HomePageActivity.this, "Please wait", "Loading...");
}

@Override
protected String doInBackground(String... params) {
String json=null;
String json2=null;
byte[] data;
StringBuffer buffer = null;
InputStream is = null;



try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", uname));

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PROFILE_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpClient.execute(httpPost);

HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
Log.e("Profile JSON: ", json.toString());

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}

@Override
protected void onPostExecute(String json){
super.onPostExecute(json);

loadingDialog.dismiss();

try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");



fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);

if(json!=null)
{
Intent i = new Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra(u.username(), u.getUsername());
i.putExtra("password",Password);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}



}catch(Exception e)
{
e.printStackTrace();
}



}
}//end of profileasynctask

最佳答案

是的,您可以发送多个网址作为参数,所有网址都将作为参数数组提供,如 params[0]、params[1],您可以循环它来发送多个请求,但我建议不要在单个 AyncTask 因为它会花费大量时间,并且如 Android 开发人员指南中所述,AsyncTask 应该用于需要工作线程的短操作,您可以在此处阅读 - https://developer.android.com/reference/android/os/AsyncTask.html

如果您想发送多个请求,请尝试使用著名的网络库(例如 Retrofit),或者如果您想使用 AsynTask,请为每个请求编写一个单独的任务。

关于java - 异步任务中的多个操作 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45967287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com