need help, got confuse with AsyncTask

后端 未结 4 1638
-上瘾入骨i
-上瘾入骨i 2021-01-29 07:44

I\'m new in android and i need to make AsyncTask, so my application can work on ICS. But after I read tutorials i still got confuse. Anyone, please help me to fix my code, i don

相关标签:
4条回答
  • 2021-01-29 08:18

    Try below code:

    public class Login extends Activity {
        public Koneksi linkurl;
        String SERVER_URL;
        private Button login, register, setting;
        private EditText username, password;
        public ProgressDialog progressDialog;
    
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
    
            setting = (Button)findViewById(R.id.bsetting);
            login = (Button) findViewById(R.id.login);
            register = (Button) findViewById(R.id.reg);
            username = (EditText) findViewById(R.id.uname);
            password = (EditText) findViewById(R.id.pass);
    
            setting.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intentSet = new Intent(Login.this, UrlSetting.class);
                    startActivity(intentSet);
                }
            });
    
            register.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intentReg = new Intent(Login.this, Register.class);
                    startActivity(intentReg);
                }
            });
    
            login.setOnClickListener(new OnClickListener() {
    
                public void onClick(View v) {
                   new LoginTask.execute();
                }
            });
    
    
        }
        protected String tryLogin(String mUsername, String mPassword)
        {           
          Log.d(" TryLoginCheck ","Here");
            HttpURLConnection connection;
           OutputStreamWriter request = null;
    
                URL url = null;
                String response = null;   
                String temp=null;
                String parameters = "username="+mUsername+"&password="+mPassword;   
                System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
                Log.d("Parameters",parameters);
                try
                {
                    ;
                    linkurl = new Koneksi(this);
                    SERVER_URL = linkurl.getUrl();
                    SERVER_URL += "/mobile/Login.php";
                    url = new URL(SERVER_URL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setRequestMethod("POST");    
    
                    request = new OutputStreamWriter(connection.getOutputStream());
                    request.write(parameters);
                    request.flush();
                    request.close();            
                    String line = "";               
                    InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                    BufferedReader reader = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null)
                    {
    
                        sb.append(line + "\n");
                    }
                    temp=sb.toString();
                    Log.d("Temp",temp);
    
                    response = sb.toString();
                    Log.d("Response",response);
                   Log.d("Sb Value",sb.toString());
                    isr.close();
                    reader.close();
    
    
                }
                catch(IOException e)
                {
                    Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
                }
    
                return response;
        }
    
        class LoginTask extends AsyncTask<String, Void, String> {
            private ProgressDialog progressDialog;
            private Login activity;
            private int id = -1;
    
            public LoginTask(Login activity, ProgressDialog progressDialog)
            {
            this.activity = activity;
            this.progressDialog = progressDialog;
            }
            @Override
            protected void onPreExecute()
            {
            progressDialog.show();
            }
            @Override
            protected Integer doInBackground(String... arg0)
            {
             String mUsername = username.getText().toString();
                    String mPassword = password.getText().toString();
    
                    response = tryLogin(mUsername, mPassword).trim();
               return response;
            }
          protected Void onPostExecute(String result){
             super.onPostExecute(result);
             if(response.toLowerCase().contains("berhasil"))
                    {
                        String nama = username.getText().toString();
                        Intent newIntent = new Intent(Login.this, MainPage.class);
    
                        Bundle bundle = new Bundle();
    
                        bundle.putString("nama", nama);
    
                        newIntent.putExtras(bundle);
                        startActivityForResult(newIntent, 0);
                    }
                    else
                    {
                        String RoleError = "ROLE SALAH";
                        String UserError = "USER SALAH";
    
                        createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
                    }
          }
        }
        private void createDialog(String title, String text) {
            AlertDialog ad = new AlertDialog.Builder(this)
            .setPositiveButton("Ok", null)
            .setTitle(title)
            .setMessage(text)
            .create();
            ad.show();
        }
    }
    
    0 讨论(0)
  • 2021-01-29 08:21

    use like that

    class LoginTask extends AsyncTask<String, Void, Integer> {
            private ProgressDialog progressDialog;
    
    
            @Override
            protected void onPreExecute()
            {
            progressDialog.show();
            }
            @Override
            protected Integer doInBackground(String... arg0)
            {
            // do all login request here only 
          }
       @Override
            protected String onPostExecute(String arg0)
            {
             progressDialog.dismiss();
    
            // get the response here and show where you want
          }
    
    0 讨论(0)
  • 2021-01-29 08:23

    Put in your OnClick method

    new LoginTask().execute(stringParam);
    

    to execute your method after clicking element.

    0 讨论(0)
  • 2021-01-29 08:23

    In short:

    You need to put your tryLogin() code into the doInBackground() method of the AsyncTask.

    Incidentally, you should really take a look at your variable naming, the scope of your methods etc. Does tryLogin() really need to be protected? mUsername and mPassword are not member variables of the class, they are local variables.

    http://source.android.com/source/code-style.html

    0 讨论(0)
提交回复
热议问题