简体   繁体   中英

Android: start a new Activity in onPostExecute() when two strings are equal

I am new to Android development.

I'm trying to create a login with an AsyncTask .

The issue I'm having is that I can't open a new Activity on onPostExecute() .

I don't know why, but my app won't run if the if(res=="valid") in postdata. In the log I can see only my response and not my response2 .

Here's the code:

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);
}

It should be

if(res.equals("valid")) {
    ...
}

When using if(res =="valid") you compare the strings by reference. Please, see How do I compare strings in Java? .

you should write:

if ("valid".equals(res)) {
}

Also, you should not call onPostExecute in doInBackground . It will be automatically called when the AsyncTask has finished executing.

The problem is because you are calling onPostExecute() explicitly. You want to return the result from postData in doInBackground() as a boolean value. I have verified that this works.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM