简体   繁体   中英

Java Android - AsyncTask onPostExecute Not getting called

So I have been trying to workout an authentication system for my app. I have a REST API running, which is tested to work with Oauth2 authentication using CURL from my laptop, so that I can get tokens for the API.

My result variable within the doInBackground does get a JSON response from my API, giving the access token information, its life, etc.

Like I get this value in result when I debug: {"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}

However, my onPostExecute for some reason is not getting called.

Here is my code.

login.java

public class Login extends AppCompatActivity {

    Button LoginButton, RegButton;
    EditText uUserName, uPassWord;
    WSAdapter.SendAPIRequests AuthHelper;

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

        //SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);

        LoginButton = (Button) findViewById(R.id.LoginButton);
        RegButton = (Button) findViewById(R.id.LoginRegister);

        uUserName = (EditText) findViewById(R.id.LoginUserBox);
        uPassWord = (EditText) findViewById(R.id.LoginPassBox);

        //AuthHelper = new WSAdapter().new SendDeviceDetails();

        // Moves user to the main page after validation
        LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // gets the username and password from the EditText
                String strUserName = uUserName.getText().toString();
                String strPassWord = uPassWord.getText().toString();

                // API url duh
                String APIUrl = "http://192.168.0.18:8000/auth/token/";

                // If the user is authenticated, then transfer to the MainActivity page
                if (APIAuthentication(strUserName, strPassWord, APIUrl)){
                    startActivity(new Intent(Login.this, Posts.class));
                }
            }
        });


        RegButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // gets the username and password from the EditText
                startActivity(new Intent(Login.this, Register.class));
            }
        });

    }

    private boolean APIAuthentication(String un, String pw, String url){
        // when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
        AuthHelper = new WSAdapter.SendAPIRequests();
        try {

            // Putting the data to be posted in the Django API
            AuthHelper.execute(un, pw, url);

            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return false;
    }
}

WSAdapter.java

public class WSAdapter {
    static public class SendAPIRequests extends AsyncTask<String, String, String> {

        // Add a pre-execute thing

        @Override
        protected String doInBackground(String... params) {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

            Log.e("TAG", params[0]);
            Log.e("TAG", params[1]);
            //String data = "";

            StringBuilder result = new StringBuilder();

            HttpURLConnection httpURLConnection = null;
            try {

                // Sets up connection to the URL (params[0] from .execute in "login")
                httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();

                // Sets the request method for the URL
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                httpURLConnection.setRequestProperty("Accept","application/json");

                // Tells the URL that I am sending a POST request body
                httpURLConnection.setDoOutput(true);
                // Tells the URL that I want to read the response data
                httpURLConnection.setDoInput(true);

                // JSON object for the REST API
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
                jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
                jsonParam.put("username", params[0]);
                jsonParam.put("password", params[1]);
                jsonParam.put("grant_type", "password");

                Log.i("JSON", jsonParam.toString());

                // To write primitive Java data types to an output stream in a portable way
                DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                // Writes out a byte to the underlying output stream of the data posted from .execute function
                wr.writeBytes(jsonParam.toString());
                // Flushes the jsonParam to the output stream
                wr.flush();
                wr.close();

                // // Representing the input stream
                InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                // reading the input stream / response from the url
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // Disconnects socket after using
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }

            Log.e("TAG", result.toString());
            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            //super.onPostExecute(result);
            // expecting a response code fro my server upon receiving the POST data
            Log.e("TAG", result);
        }
    }

SO I actually just figured this out. It turns out that my code is running fine, its just that when I debug, I didn't realize theres a button to the side "Run the new thread" or something like that. It then sent me to the onPostExecute . Sorry for being a noob. Hopefully this can be a help to somebody in the future with this simple mistake.

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