我有一个wcf服务,根据输入返回true或false(检查用户登录)。 我试图在Android应用程序中实现它,但每当我按下按钮时,应用程序崩溃。 这是代码:
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
email = editEmail.getText().toString();
pass = editPass.getText().toString();
if(email.matches("") || pass.matches("")){
txtresult.setText("Please fill in the information!");
return;
}
if(!isConnected){
txtresult.setText("You don't have internet connection!");
return;
}
new MyTask().execute();
if(status.equals("true")){
//savePreferences();
finish();
}
else{
txtresult.setText("Wrong login information!");
}
}
});
AsyncTask:
public class MyTask extends AsyncTask<Void,Void,Void> {
String email1 = editEmail.getText().toString();
String pass1 = editPass.getText().toString();
@Override
protected Void doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://wswob.somee.com/wobservice.svc/checkLogin/"+email1+"/"+pass1);
HttpContext localContext = new BasicHttpContext();
HttpResponse response;
try {
response = httpclient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
status = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
这工作正常并且突然停止工作......由于我2周的经验,我不确定如何调试。有什么想法吗?
答案 0 :(得分:1)
这一行:
if(status.equals("true")){
崩溃,因为status
尚未分配,抛出NullPointerException。
根据定义,AsyncTasks是异步的。这意味着一旦进行异步调用,代码控件将立即返回并在另一个线程中启动异步工作。
执行此操作的正确方法是使用AsyncTask回调onPostExecute()
,并在那里检查您的状态。
public class MyTask extends AsyncTask<Void,Void,Void> {
String email1 = editEmail.getText().toString();
String pass1 = editPass.getText().toString();
@Override
protected Void doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://wswob.somee.com/wobservice.svc/checkLogin/"+email1+"/"+pass1);
HttpContext localContext = new BasicHttpContext();
HttpResponse response;
try {
response = httpclient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
status = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected Void onPostExecute(Void result){
super.onPostExecute(result);
//TODO: your code here. check your status and handle from there
}
}