我的Android应用程序中有一个小问题,我正在尝试将数组列表传递给asynctask以将一些数据发布到外部api。但是eclipse总是返回一个数据类型错误,我无法想象如何将params从活动传递给ASyncTask。请帮忙
public void Login(View view){
String usern = username.getText().toString();
String pwd = password.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", usern));
nameValuePairs.add(new BasicNameValuePair("password", pwd));
nameValuePairs.add(new BasicNameValuePair("external-login", "true"));
if(isNetworkAvailable()){
GetAxiomaCredentials axiomacredentials = new GetAxiomaCredentials();
axiomacredentials.execute();
}else{
Toast.makeText(this, "Network is not available.", Toast.LENGTH_LONG).show();
}
}
所以我可以传递nameValuePairs来作为参数执行但是我从AsyncTask Private类中得到一个错误的类型错误
private class GetAxiomaCredentials extends AsyncTask<ArrayList<String>, Integer, String>{
private static final String POST_URL = "http://192.168.0.105/index.php/r=rsite/heartbeat";
@Override
protected String doInBackground(ArrayList<String>... params) {
int responseCode = -1;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(POST_URL);
try {
// Add your data
ArrayList<String> data = params[0];
httppost.setEntity(new UrlEncodedFormEntity(data));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return "Code: " + responseCode;
}
@Override
protected void onProgressUpdate(Integer... progress) {
}
public void postData(String name, String email, String password,String mobile) {
// Create a new HttpClient and Post Header
}
}
我得到的eclipse编译错误就在这一行:
ArrayList<String> data = params[0];
httppost.setEntity(new UrlEncodedFormEntity(data));
那么如何解决此问题以将所有参数从活动中的Login操作传递给AsyncTask? 感谢
答案 0 :(得分:1)
将输入更改为doInBackground到ArrayList。这将删除强制转换异常。
private class GetAxiomaCredentials extends AsyncTask<Object, Integer, String>{
...
将ArrayList更改为Object
protected String doInBackground(Object... params) {
int responseCode = -1;
List<NameValuePair> data = (List<NameValuePair>) params[0];
...
然后当你调用execute时,传入nameValuePairs
if(isNetworkAvailable()){
GetAxiomaCredentials axiomacredentials = new GetAxiomaCredentials();
axiomacredentials.execute(nameValuePairs);
答案 1 :(得分:1)
只需在GetAxiomaCredentials
类中添加构造函数即可。构造函数应该将List
对象作为参数,然后将其存储在类变量中,然后在doInBackground()
中使用它。
有些事情如下:
private class GetAxiomaCredentials extends AsyncTask<ArrayList<String>, Integer, String> {
private List<NameValuePair> nvp;
public GetAxiomaCredentials(List<NameValuePair> nvp) {
this.nvp = nvp;
}
/*
use this.nvp in doInBackground(), onPostExecute(), etc...
*/
}
在您的主要课程中执行以下操作:
GetAxiomaCredentials axiomacredentials = new GetAxiomaCredentials(nameValuePairs);
axiomacredentials.execute();
<强>更新强>
UrlEncodedFormEntity
没有构造函数需要List<String>
个对象。它只接受List<? extends NameValuePair>
。这就是为什么它不会编译。