Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Help Understanding Java AsyncTask Code

Posted on 2014-11-24
5
Medium Priority
?
227 Views
Last Modified: 2014-11-28
Hello,

Creating Java project in Android Studio 0.8.14.  Learning to use AsyncTask to send HTTPRequest with JSON parameters and response.  

The following code works great.  It sends the parameters to URL and properly evaluates Login Failure or Login Success.  Problem is that I don't understand how to use that response in the rest of my program.

Specifically, how do I use the returned values in lines 98 and 101 to change the tvwStatus TextView in my Layout?

package com.android.json.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class Login extends Activity implements OnClickListener {

    private EditText editUsername, editPassword;
    private TextView tvwStatus;
    private Button btnLogin;

    JSONParser jsonParser = new JSONParser();

    private static final String LOGIN_URL = "http://m.binghamtonyoga.com/login.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // *** Setup GUI Objects ***
        editUsername = (EditText)findViewById(R.id.editUsername);
        editPassword = (EditText)findViewById(R.id.editPassword);
        tvwStatus = (TextView)findViewById(R.id.tvwStatus);
        btnLogin = (Button)findViewById(R.id.btnLogin);

        // *** Register OnClick Listener ***
        btnLogin.setOnClickListener(this);
    }

    public void onClick(View v) {
        // *** Which Button was Clicked? ***
        switch (v.getId()) {
            case R.id.btnLogin:
                new AttemptLogin().execute();
                break;
            default:
                break;
        }
    }

    // ***************************************************************************
    // Async Task to Attempt Login
    // ***************************************************************************
    class AttemptLogin extends AsyncTask<String,Void,String> {

        boolean failure = false;

        @Override
        protected String doInBackground(String... args) {

            // Check for success tag
            int success;
            String username = editUsername.getText().toString();
            String password = editPassword.getText().toString();
            try {
                // *** Build Parameters ***
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUsername", username));
                params.add(new BasicNameValuePair("txtPassword", password));

                // *** Make HTTP Request to Login with Parameters ***
                Log.d("***HTTPRequest URL:", LOGIN_URL);
                Log.d("***HTTPRequest Type:", "POST");
                Log.d("***HTTPRequest Param(0):", params.get(0).toString());
                Log.d("***HTTPRequest Param(1):", params.get(1).toString());
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
                Log.d("***HTTPRequest Response:", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("***LOGIN SUCCESS***", json.toString());
                    Intent i = new Intent(Login.this, Layout.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("***LOGIN FAILURE***", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Open in new window


Thank you!

Jason
0
Comment
Question by:SqueezeOJ
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 21

Expert Comment

by:MogalManic
ID: 40464504
The code you listed builds a JSON request and posts it to your login page.

When the login is successful it finishes the activity.  The success path also generates a new 'Intent' class that is used in asynchronous binding.  If the login is unsuccessful the activity is not finished.

Do you want to somehow record the logged in user?
0
 

Author Comment

by:SqueezeOJ
ID: 40464607
Hi Mogal - Thanks for responding!

On lines 98 and 101 the code is returning a value, however, (as a very newbie-Java programmer) I couldn't figure out to where.

After showing the code to a friend last night, we figured out that line 56 instantiates the AttemptLogin class, but doesn't assign the value to anything.  So any value returned from AttemptLogin simply disappears and the program ends.  They suggested that I change line 56 to look something like this:
myvar=new AttemptLogin().execute();

Open in new window


Does that make sense to you?  Is that the best way to "inform" the Login class of the AttemptLogin's outcome?
0
 

Author Comment

by:SqueezeOJ
ID: 40464646
So, I tried this:
String myResult;
myResult = new AttemptLogin().execute();

Open in new window

But the IDE underlines it and says "Incompatible Types".

How do I get the return statements on lines 98 and 101 to share their outcome with my calling statement on line 56?
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 2000 total points
ID: 40467266
A more correct example can be found at http://nads-rosun.blogspot.com/2014/01/android-login-application-using.html

The background task handles the completion of the background task on the   protected void onPostExecute(String result)  function.  It never "Finishes" the activity.  Instead, it creates an "intent" on the OnPostExecute
    Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
     startActivity(i);
this will transfer control to the new activity.
0
 

Author Closing Comment

by:SqueezeOJ
ID: 40470882
Thanks!  I'm beginning to understand these "intents".
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question