簡體   English   中英

Android - 執行 AsyncTask 線程時出現問題

[英]Android - Problem with executing AsyncTask thread

我正在嘗試編寫一個在異步任務上發送POST請求的應用程序。 我的AsyncTask似乎沒有執行,因為我的進度條沒有出現。 我真的不知道這里出了什么問題,因為我遵循了許多解決方案/教程。 這是我的代碼:

寄存器.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;
        }
    }
}

這是注冊DB.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);
    }
}

我有外部 class openHTTP.java負責打開 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;
    }
}

提前感謝您的幫助!

更新

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

我的解決方案

因此,在 AndroidManifest.xml 中添加android:usesCleartextTraffic="true"就足夠了,感謝您的幫助!

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

因此,在 AndroidManifest.xml 中添加android:usesCleartextTraffic="true"就足夠了,感謝您的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM