Why Not Generic AsyncTask Class? Before we get started, let me say welcome to KosalGeek. I am glad you came! OK, I got it. You came because you are like me; we are tired of creating tons of classes (mostly private classes) of AsyncTask class all over an over again. Motivation If you don’t know what I am talking, let me explain a bit. Basically, in Android whenever you want to connect to an external source, you use AsyncTask. You can use Handler but it is a different approach which is not covered in this page. Most of the time, we use it to connect to a web service to retrieve data in JSON or XML format (the latter is not common) from a database server (e.g. MySQL), and to send data (HttpPost, HttpGet) to a web service. For example, if you want to let clients register from your Android app, then there are data send back and forth. See the illustration of how it works: For a Website, this would look very simple because it is the nature of a Web. However, for an app, not just Android app, this would make a day or two. Why? One request from a client is one private class extending AsyncTask. Another response from a web service to a client becomes another private AsyncTask class. Let me write some codes to show you how to do a login from Android to PHP to MySQL. It is not limited to PHP and MySQL, you can use your favorite language and database server. If you know how to do it, you are free to skip to the
Create Generic AsyncTask section. Create a Database in MySQL First, let me create db_client database and tbl_client table with 4 attributes (id, full name, username, password).

CREATE DATABASE db_client;

CREATE TABLE tbl_client
(id INTEGER PRIMARY KEY NOT NULL,
name VARCHAR(50) NOT NULL,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);

INSERT INTO tbl_client(name, username, password) VALUES('Kosal Geek', 'kosalgeek', 'xyz');

INSERT INTO tbl_client(name, username, password) VALUES('abc', 'abc', '123');

INSERT INTO tbl_client(name, username, password) VALUES('Test', 'test', 'test');

Create a Login Page in PHP connection.php Below is the connection file:

 

login.php Make sure you place json.php in the same folder of connection.php


Password 

 

Create a Login Activity in Android
Check out how to install Android Studio if you don’t have Android Studio yet.
XML for User Interface
res/activity_login.xml

Java Code
src/com.yourpackage.login/LoginActivity.java

public class LoginActivity extends Activity implements OnClickListener {

  EditText etUsername, etPassword;
  Button btnLogin;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLogin.setOnClickListener(this);
  }
  
  @Override
  public void onClick(View sender) {
    if (sender.getId() == R.id.btnLogin) {
      LoginTask loginTask = new LoginTask();
      loginTask.execute("http://10.0.2.2/movie_ticket/login.php");
    }
  }

  private class LoginTask extends AsyncTask<String, Void, Void> {

    ProgressDialog dialog = new ProgressDialog(LoginActivity.this);

    @Override
    protected void onPreExecute() {
      dialog.setMessage("Login...");
      dialog.show();
    }

    Boolean result = false;

    InputStream is1;
    String text = "";
    private String error = "";

    @Override
    protected Void doInBackground(String... urls) {
      for (String url1 : urls) {

        try {
          ArrayList pairs = new ArrayList();
          pairs.add(new BasicNameValuePair("txtUsername", etUsername.getText().toString()));
          pairs.add(new BasicNameValuePair("txtPassword", etPassword.getText().toString()));
          pairs.add(new BasicNameValuePair("mobile", "android"));
          HttpClient client = new DefaultHttpClient();
          HttpPost post = new HttpPost(url1);
          post.setEntity(new UrlEncodedFormEntity(pairs));
          HttpResponse response = client.execute(post);
          is1 = response.getEntity().getContent();  

          result = true;

        } catch (ClientProtocolException e) {
          error += "\nClientProtocolException: " + e.getMessage();
        } catch (IOException e) {
          error += "\nClientProtocolException: " + e.getMessage();
        }

        BufferedReader reader;

        try {
          reader = new BufferedReader(new InputStreamReader(is1, "iso-8859-1"), 8);
          String line = null;

          while ((line = reader.readLine()) != null) {
            text += line + "\n";
          }
        } catch (UnsupportedEncodingException e) {
          error += "\nClientProtocolException: " + e.getMessage();
        } catch (IOException e) {
          error += "\nClientProtocolException: " + e.getMessage();
        }
      }
      return null;
    }

    @Override
    protected void onPostExecute(Void arg0) {
      if (dialog.isShowing()) {
        dialog.dismiss();
      }

      text = text.trim();

      Toast.makeText(LoginActivity.this, text, Toast.LENGTH_LONG).show();

      if (text.equals("login_success")) {
        Intent in = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(in);
      } else {
        Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_SHORT).show();
      }
    }
  }
}

Comments

comments