在哪里放AsyncTask

时间:2013-09-02 01:44:49

标签: android android-asynctask

我正在遵循这里的教程:http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/当我运行编码时出现ANR错误,所以我被告知在RegisterActivity.java和LoginActivity.java的OnClick方法上创建一个AsyncTask(我正在创建一个用户数据库) 这是由androidhive教程定义的RegisterActivity.java和LoginActivity.java:

RegisterActivity.java

package com.example.dashboardactivity;

import org.json.JSONException;
import org.json.JSONObject;

import libary.DatabaseHandler;
import libary.UserFunctions;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterActivity extends Activity {
public final String TAG = "LoginActivity";
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    // Importing all assets like buttons, text fields
    inputFullName = (EditText) findViewById(R.id.registerName);
    inputEmail = (EditText) findViewById(R.id.registerEmail);
    inputPassword = (EditText) findViewById(R.id.registerPassword);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
    registerErrorMsg = (TextView) findViewById(R.id.register_error);

    // Register Button Click event
    Log.i(TAG, "RegisterActivity Register button Click Event" );
    btnRegister.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.registerUser(name, email, password);

            // check for login response
            Log.i(TAG, "RegisterActivity check for login response" );
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){
                        // user successfully registred
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        userFunction.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                        // Launch Dashboard Screen
                        Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        // Close Registration Screen
                        finish();
                    }else{
                        // Error in registration
                        registerErrorMsg.setText("Error occured in registration");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

    // Link to Login Screen
    Log.i(TAG, "RegisterActivity Link to Login Screen" );
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            // Close Registration View
            finish();
        }
    });
}
}

LoginActivity.java

package com.example.dashboardactivity;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import libary.DatabaseHandler;
import libary.UserFunctions;

public class LoginActivity extends Activity {
public final String TAG = "LoginActivity";
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.loginEmail);
    inputPassword = (EditText) findViewById(R.id.loginPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);

    // Login button Click Event
    Log.i(TAG, "LoginActivity Login button Click Event" );
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email, password);
 Log.i(TAG, "checking for login response");
            // check for login response
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    loginErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){
                        // user successfully logged in
                        // Store user details in SQLite Database
                        libary.DatabaseHandler db = new libary.DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        userFunction.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        

                        // Launch Dashboard Screen
                        Log.i(TAG, "LoginActivity Launch Dashboard Screen" );
                        Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);

                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);

                        // Close Login Screen
                        finish();
                    }else{
                        // Error in login
                        loginErrorMsg.setText("Incorrect username/password");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

    // Link to Register Screen
    Log.i(TAG, "LoginActivity btnLinkToRegister" );
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
            finish();
        }
    });
}
}

现在我担心如果我完全更改OnClick方法,我的应用程序将不会运行相同的。有人告诉我使用编码:

// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
    new AsyncTask<String, Void, JSONObject>(){
        @Override
        protected JSONObject doInBackground(String... args) { //This is run on a background thread
            String email = args[0];
            String password = args[1];
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email, password);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) { //This is run on the UI thread
            if(json != null){
                //... update the user interface ...
            }else{
                Log.e("LoginTask", "No login response was received");
            }
            super.onPostExecute(json);
        }

    }.execute(inputEmail.getText().toString(), inputPassword.getText().toString());
}
});

我之前从未使用过AsyncTasks,所以我应该将当前编码切换为我作为模板提供的编码,如果是这样会影响我的应用程序的工作方式?或者我应该将编码实现为新的AsyncTask,我将把它放在我的RegistrationActivity.java/LoginActivity.java中?谢谢你的时间。

0 个答案:

没有答案