Java Android - AsyncTask onPostExecute Не вызывается - PullRequest
0 голосов
/ 17 февраля 2019

Итак, я пытался разработать систему аутентификации для своего приложения.У меня работает REST API, который протестирован для работы с аутентификацией Oauth2 с использованием CURL с моего ноутбука, чтобы я мог получить токены для API.

Моя переменная result в doInBackground действительно получает ответ JSON от моего API, предоставляя информацию о токене доступа, его жизнь и т. Д.

Как будто я получаю это значение в result когда я отлаживаю: {"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}

Однако мой onPostExecute по какой-то причине не вызывается.

Вот мой код.

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

1 Ответ

0 голосов
/ 18 февраля 2019

ТАК Я действительно только что понял это.Оказывается, мой код работает нормально, просто, когда я отлаживал, я не понимал, есть ли кнопка «Запустить новый поток» или что-то в этом роде.Затем он отправил меня на onPostExecute.Извините за то, что я нуб.Надеюсь, это поможет кому-то в будущем с этой простой ошибкой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...