[英]Can't able to start new activity from onPostExecute method in Android
[英]Android: start a new Activity in onPostExecute() when two strings are equal
我是Android
开发的新手。
我正在尝试使用AsyncTask
创建登录。
我遇到的问题是我无法在onPostExecute()
上打开一个新的Activity
。
我不知道为什么,但如果postdata中的if(res=="valid")
我的应用程序将无法运行。 在log
我只能看到my response
而不是my response2
。
这是代码:
public class MainActivity extends Activity {
private EditText employeNum;
private EditText Id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
employeNum = (EditText) findViewById(R.id.editText1);
Id = (EditText) findViewById(R.id.editText2);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class MyAsyncTask extends AsyncTask<String, Integer, Double> {
// int loginVerified=0;
public boolean loginVerified = false;
public String res;
protected Double doInBackground(String... params) {
postData(params[0],params[1]);
return null;
}
protected void onPostExecute(boolean loginVerified){
if(loginVerified == true)
{
Intent menu = new Intent(getApplicationContext(),menu.class);
startActivity(menu);
finish();
}
}
public void postData(String a,String b) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.nir-levi.com/login/");
try {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("user_email", a));
nameValuePair.add(new BasicNameValuePair("user_password", b));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
res = sb.toString();
if(res=="valid"){
Log.v("My Response2::",res);
loginVerified=true;
onPostExecute(loginVerified);
}
Log.v("My Response::",res);
public void login(View v) {
String num = employeNum.getText().toString();
String id = Id.getText().toString();
new MyAsyncTask().execute(num, id);
}
你应该写:
if ("valid".equals(res)) {
}
此外,你不应该叫onPostExecute
在doInBackground
。 当AsyncTask完成执行时,它将自动调用。
问题是因为您显式调用onPostExecute()。 您希望将doInBackground()中postData的结果作为布尔值返回。 我已经证实这是有效的。
public class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
private static final String TAG = "MyAsyncTask";
public boolean loginVerified = false;
public String res;
protected Integer doInBackground(String... params) {
try {
// return the boolean loginVerified
return postData(params[0], params[1]);
} catch (IOException e){
Log.e(TAG, "doInBackground()", e);
return false; // <- return the boolean loginVerified
}
}
protected void onPostExecute(Boolean loginVerified){
if(loginVerified == true) {
Intent menu = new Intent(getApplicationContext(), menu.class);
startActivity(menu);
finish();
}
}
private boolean postData(String a, String b) throws IOException {
URL url = new URL("http://www.nir-levi.com/login/");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
connection.setRequestMethod(POST);
connection.setRequestProperty(KEY_USER_AGENT, USER_AGENT);
connection.setDoOutput(true);
DataOutputStream urlOutput = new DataOutputStream(connection.getOutputStream());
urlOutput.writeBytes(urlBody);
urlOutput.flush();
urlOutput.close();
int responseCode = connection.getResponseCode();
InputStream in = null;
if (responseCode == 201){ /* Hopefully your server is sending the
proper Http code for a successful
create */
in = connection.getInputStream();
} else {
in = connection.getErrorStream();
}
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
byteArrayOut.write(buffer, 0, bytesRead);
}
byteArrayOut.close();
res = new String(byteArrayOut.toByteArray();
Log.v(TAG, "res = " + res);
return (res.compareTo("valid") == 0); // <- return from postData
} catch (FileNotFoundException e){
Log.e(TAG, "Error: " + connection.getResponseCode(), e);
return false;
} finally {
connection.disconnect();
}
}
public void login(View v) {
String num = employeNum.getText().toString();
String id = Id.getText().toString();
new MyAsyncTask().execute(num, id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.