-1

我是 android 新手,我需要制作 AsyncTask,所以我的应用程序可以在 ICS 上运行。但是在我阅读教程后,我仍然感到困惑。任何人,请帮我修复我的代码,我不知道我必须用这样的代码在 AsyncTask 中放入什么以及在哪里。谢谢你

登录.java

package com.karismaelearning;

public class Login extends Activity {
    public Koneksi linkurl;
    String SERVER_URL;
    private Button login, register, setting;
    private EditText username, password;
    public ProgressDialog progressDialog;

    @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) {
                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) {
                String response = null;
                String mUsername = username.getText().toString();
                String mPassword = password.getText().toString();

                response = tryLogin(mUsername, mPassword).trim();

                Log.d("Check","Here");
                Log.d("Response",response);

                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
                {
                    //Optional
                    //Kalau bisa dibuat constant untuk menghindari salah penulisan
                    String RoleError = "ROLE SALAH";
                    String UserError = "USER SALAH";

                    createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
                }
            }
        });


    }
    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, Integer> {
        public LoginTask(Login activity, ProgressDialog progressDialog){
        }
        @Override
        protected void onPreExecute(){
        progressDialog.show();
        }
        @Override
        protected Integer doInBackground(String... arg0){
    }
    private void createDialog(String title, String text) {
        AlertDialog ad = new AlertDialog.Builder(this)
        .setPositiveButton("Ok", null)
        .setTitle(title)
        .setMessage(text)
        .create();
        ad.show();
    }
}

login.java - 已编辑 -> 是这样的吗?

package com.karismaelearning;

public class Login extends Activity {
    public Koneksi linkurl;
    String SERVER_URL;
    private Button login, register, setting;
    private EditText username, password;
    public ProgressDialog progressDialog;
    @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) {
                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;
    }

    public class LoginTask extends AsyncTask<String, Void, String> {
        String response = null;
        public LoginTask() {
        }
        @Override
        protected void onPreExecute(){
        }
        @Override
        protected String 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);
         Log.d("Check","Here");
            Log.d("Response",response);

            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{
                //Optional
                //Kalau bisa dibuat constant untuk menghindari salah penulisan
                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();
    }
}
4

4 回答 4

1

像这样使用

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
      }
于 2013-06-10T06:24:04.767 回答
1

输入你的OnClick方法

new LoginTask().execute(stringParam);

单击元素后执行您的方法。

于 2013-06-10T06:26:24.217 回答
0

简而言之:

您需要将 tryLogin() 代码放入 AsyncTask 的 doInBackground() 方法中。

顺便说一句,你真的应该看看你的变量命名、方法的范围等。tryLogin() 真的需要保护吗?mUsername 和 mPassword 不是类的成员变量,它们是局部变量。

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

于 2013-06-10T06:20:00.693 回答
0

试试下面的代码:

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();
    }
}
于 2013-06-10T06:26:33.540 回答