简体   繁体   中英

Android - Problem with executing AsyncTask thread

I'm trying to write an app that sends a POST request on asynchronous task. My AsyncTask does not seem to execute since my progress bar doesn't show up. I don't really know what is wrong here, since I followed many solutions/tutorials. Here's my code:

register.java

public class register extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        final Activity thisActivity = this;
        final EditText userNameEditText = findViewById(R.id.registerUsername);
        final EditText emailEditText = findViewById(R.id.registerEmail);
        final EditText passwordEditText = findViewById(R.id.registerPassword);
        final ProgressBar progressBar = findViewById(R.id.progressBar);
        Button btnRegisterDB = findViewById(R.id.btnRegistrationDB);
        final TextView respondText = findViewById(R.id.responseRegister);
        btnRegisterDB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = String.valueOf(userNameEditText.getText());
                String email = String.valueOf(emailEditText.getText());
                String password = String.valueOf(passwordEditText.getText());
                //execute asynchronous task in background and wait for response
                RegisterParams params = new RegisterParams(username, email, password);
                registrationDB async = new registrationDB();
                async.setProgressBar(progressBar);
                async.setRespondText(respondText);
                async.getParentActivity(thisActivity);
                async.execute(params);
            }
        });
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        return true;
    }
    
    public static class RegisterParams {
        public String username;
        public String email;
        public String password;

        RegisterParams(String username, String email, String password){
            this.username = username;
            this.email = email;
            this.password = password;
        }
    }
}

and here is registrationDB.java

public class registrationDB extends AsyncTask<register.RegisterParams, Void, String> {

    openHTTP openHTTP = new openHTTP();
    String respond;

    ProgressBar pb;
    TextView respondTextView;
    Activity parentActivity;

    public void setProgressBar(ProgressBar progressBar){
        this.pb = progressBar;
    }

    public void setRespondText(TextView textView){
        this.respondTextView = textView;
    }

    public void getParentActivity(Activity parentActivity){
        this.parentActivity = parentActivity;
    }

    @Override
    public void onPreExecute(){
        pb.setVisibility(View.VISIBLE);
        //parentActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
        //        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        super.onPreExecute();
    }
    
    @Override
    protected String doInBackground(register.RegisterParams... params) {
        try {
            HttpURLConnection httpConn = openHTTP.prepareConnection("someurl");
            String jsonInputString = "{ username: " + params[0].username +", email: " + params[0].email
                    + ", password: " + params[0].password + "}";
            try(OutputStream os = httpConn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            } catch (Exception e){
                e.printStackTrace();
            }
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(httpConn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                respond = response.toString();
                return respond;
            } catch (Exception e){
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        pb.setVisibility(View.GONE);
        respondTextView.setText(s);
        super.onPostExecute(s);
    }
}

and I have external class openHTTP.java which is responsible for opening HttpUrlConnection:

public class openHTTP {

    public openHTTP(){

    }
    //provide URL to external file that you want make POST request to
    public HttpURLConnection prepareConnection(String URL){
        try {
            java.net.URL url = new URL(URL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);
            return con;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Thanks in advance for help!

UPDATE

After logging processes I've discovered that exception: java.io.IOException: Cleartext HTTP traffic to url not permitted , now I'm on my way searching for this problem

MY SOLUTION

So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml Thanks for your help!

After logging processes I've discovered that exception: java.io.IOException: Cleartext HTTP traffic to url not permitted .

So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml Thanks for your help!

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