我有一个安卓应用程序。
我需要在单独的任务上执行代码,因为它对我来说是 android.os.NetworkOnMainThreadException 。
这是我的代码:
public class AccesoCuentaActivity extends Activity{
public void validacion(View v) throws IOException, XmlPullParserException
{
try {
String usuario=((EditText)findViewById(R.id.etUsu)).getText().toString();
String pass=((EditText)findViewById(R.id.etPass)).getText().toString();
String[] pars = new String[2];
String[] = new String[2];
pars[0] = usuario;
pars[1] = pass;
new ValidacionThread().execute(pars);
Intent intent=new Intent(this, MainActivity.class);
intent.putExtra("idBoton",12);
intent.putExtra("usuario",usu);
startActivityForResult(intent, 0);
} }
任务:
public class ValidacionThread extends AsyncTask<String, Void, Usuario> {
private final String NAMESPACE = "http://webservices.pcp/";
private final String URL = "http://127.0.0.1:8080/webServices/pcpWS?wsdl";
private final String SOAPACTION = "";
private final String METHOD = "ValidarUsuario";
protected Usuario doInBackground(String[] pars) {
String user = pars[0];
String password = pars[1];
SoapObject request = new SoapObject(NAMESPACE, METHOD);
SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
sobre.dotNet = false;
request.addProperty("login", user);
request.addProperty("password", password);
sobre.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(SOAPACTION, sobre);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SoapObject resultado = null;
try {
resultado = (SoapObject)sobre.getResponse();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Usuario usu = new Usuario();
usu.IdUsuario= resultado.getProperty(0).toString();
usu.Nombre = resultado.getProperty(1).toString();
usu.Apellidos = resultado.getProperty(2).toString();
usu.Rol = resultado.getProperty(3).toString();
usu.Centro=resultado.getProperty(4).toString();
return usu;
}
protected void onPostExecute(ValidacionThread vt) {
}
}
它给了我两个问题:
1) 在 AccesoCuentaActivity 类中:
我想将变量“usuario”返回保存在ValidationThread.doInBackground()中。但是我该怎么做呢?
事实上,如果我只是写: new ValidacionThread().execute(pars); 它告诉我变量 "usu" (intent.putExtra("usuario",usu);) 尚未初始化
while with code (in main code) Usuario usu = new ValidacionThread().execute(pars); 它说类型不匹配
2)doInBackground()
在线eclipse给出警告:可变参数方法应该只覆盖或被其他可变参数方法覆盖,不像ValidacionThread.doInBackground(String[])
和AsyncTask<String,Void,Usuario>.doInBackground(String...)