Ameen OT
Ameen OT

Reputation: 170

Return a value from one activity to another

I want to display a message if the user types wrong password or username.

This is the class which takes the values

    public class Login extends Activity {

    Button submit_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        submit_login = (Button) findViewById(R.id.submit_login);
        submit_login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub.
                EditText usr_number = (EditText) findViewById(R.id.username);
                EditText password_main = (EditText) findViewById(R.id.password);
                String username = usr_number.getText().toString();
                String password = password_main.getText().toString();
                String[] Loginvalues = {username,password};

                new CheckUsername().execute(Loginvalues);

            }
        });
    }

}

Now After new CheckUsername().execute(Loginvalues); this call i want to show a message in textview( id = loginStatus)

public class CheckUsername extends AsyncTask<String, Integer, String[]> {

    HttpClient Client;
    JSONObject json;
    final static String URL = "someurl";

    @Override
    protected String[] doInBackground(String... params) {
        // TODO Auto-generated method stub
        String username = params[0].toString();
        String password = params[1].toString();
        Client = new DefaultHttpClient();
        try {
            json = ValidateUsername(username, password);

            String status = json.getString("status");
            if (status.equals("ok")) {

                System.out.println(json.getString("response"));

                JSONObject user_values = new JSONObject(json.getString("user"));

                GlobalVariables newObj = new GlobalVariables();

                newObj.setUserId(user_values.getString("id"));

                newObj.setUserName(user_values.getString("name"));

                System.out.println(newObj.getUserId());

                System.out.println(newObj.getUserName());
            } else {

            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject ValidateUsername(String username, String password)
            throws ClientProtocolException, IOException, JSONException {
        StringBuilder url = new StringBuilder(URL);
        HttpPost post = new HttpPost(url.toString());
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("token", "ABCD"));
            nameValuePairs.add(new BasicNameValuePair("func_name",
                    "validate_user"));
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = Client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity e = response.getEntity();
                String data = EntityUtils.toString(e);

                JSONObject statusValue = new JSONObject(data);
                return statusValue;

            } else {
                System.out.println(status);
                return null;
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

}

status.equals("ok") this is the identifier which lets us know if logged or not

Thanks

Upvotes: 1

Views: 94

Answers (2)

zgc7009
zgc7009

Reputation: 3389

It appears you might be misunderstanding the functionality of an AsyncTask, or just haven't read up on it too much. A big piece of clarification is that an AsyncTask is not an Activity. It is important to understand what an Activity is and how it is used to interact with the UI (it is one of a handful of classes that will let you do that).

Helping with your question, instead of having a separate class, just put your AsyncTask as a inner class of your main class.

public class Login extends Activity {
    // Your code like onCreate and stuff

    public class CheckUsername extends AsyncTask<String[], Void, String> {
        // do your async task stuff
    }
}

Extending on your AsyncTask, after you are done with do in background, you can return data to your class via onPostExecute()

public class CheckUsername extends AsyncTask<String[], Void, String> {
    @Override
    protected String doInBackground(String[]... params) {
        //... do your stuff
        return statusValue;
    }

    @Override
    protected void onPostExecute(String statusValue) {
        setText(statusValue);
    }
}

In your main class, have a method like setText that will allow you to work with your return value as needed

public void setText(String return) {
    if (return.equals("ok") {    // or whatever it is supposed to equal if it's ok
         // set your text to whatever, you are ok
    }
    else {
         // set your text to whatever, bad password
    }
}

In short, the design idea behind an AsyncTask is

public class AsyncTaskName extends AsyncTask<IN_PARAMETER, PROGRESS_PARAMETER, RETURN_PARAMETER> {
    @Override
    protected RETURN_PARAMETER doInBackground(IN_PARAMETER... params) {
         // do your stuff
         return (variable of type RETURN_PARAMETER);
    }

    @Override
    protected void onProgressUpdate(PROGRESS_PARAMETER... progress) {
         // do your stuff
    }

    @Override
    protected void onPostExecute(RETURN_PARAMETER returnParam) {
         // interact with your UI, like calling a method from your activity
    }
}

It is worth noting that onProgressUpdate is often not needed for a task, unless you want to notify the user of the update progress of your AsyncTask directly.

AsyncTasks are meant to do operations off of the UI, but still be able to easily interact with it. The method doInBackground tells the AsyncTask that we want that done off of the UI thread, but onPostExecute tells us that we are done, close up our thread and return our data. Without onPostExecute you are floating dead in the water as far as UI interaction is concerned. You don't have to call a method from onPostExecute and can work with the UI directly (like textView.setText(returnValue);) but using a method makes it clearer that the work is being done by the Activity and not the AsyncTask itself.

Upvotes: 1

suraj shukla
suraj shukla

Reputation: 268

you can use

protected void onPostExecute(Void unused) {

// NOTE: You can call UI Element here.

 }

It might solve your problem.

Upvotes: 0

Related Questions