在哪里放置AsyncTask

时间:2013-06-26 03:38:21

标签: android android-asynctask

我收到有关主UI线程的错误,我不知道我应该在这段代码中放置AsyncTask类。 它应该在LoginActivity类,UserFunction类还是JSONParser类中 我还需要帮助搞清楚如何构建AsyncTask。我一直在尝试变种,但我无法弄清楚

谢谢

LoginActivity Class

ALL OTHER IMPORTS
import com.example.login.DatabaseHandler;
import com.example.login.UserFunctions;

public class LoginActivity extends Activity {
 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
    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);


            // 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
                        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 Login Screen
                        finish();
                    }else{
                        // Error in login
                        loginErrorMsg.setText("Incorrect username/password");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

UserFunction类

 ALL IMPORTS

public class UserFunctions {

private JSONParser jsonParser;

// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://10.0.2.2/loginform/reg_login/index.php/";
private static String registerURL = "http://10.0.2.2/loginform/reg_login/index.php/";

private static String login_tag = "login";
private static String register_tag = "register";

// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */



    public JSONObject loginUser(String email, String password){


    // Building Parameters
    List<NameValuePair> params1 = new ArrayList<NameValuePair>();
     params1.add(new BasicNameValuePair("tag", login_tag));
     params1.add(new BasicNameValuePair("email", email));
     params1.add(new BasicNameValuePair("password", password));

    // return json
    // Log.e("JSON", json.toString());

        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params1);
   return json;
    }

JSONParser Class

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);           
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

  }
 }

2 个答案:

答案 0 :(得分:1)

由于您无法在主UI线程中执行网络操作,因此请在执行网络操作的地方使用asynctask。

如果我没错,你的getJSONFromUrl只会进行网络操作。所以使用Asynctask

调用它

答案 1 :(得分:0)

试试这个

public class Login extends AsyncTask<Void, Void, Boolean> {
    private String email;
    private String password;
    private JSONObject json;
    public Login(String email, String password) {
        this.email = email;
        this.password = password;
    }
    @Override
    protected Boolean doInBackground(Void... params) {
        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(email, password);
        return true;

    }

    @Override
    protected void onPostExecute(Boolean status) {
         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
                        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 Login Screen
                        finish();
                    }else{
                        // Error in login
                        loginErrorMsg.setText("Incorrect username/password");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    }

}

基本上只是将你的网络进程放在doinBackground中,然后在onPostExecute中获取数据后的另一个进程

并在onClick方法中使用

调用此类
new Login(email,password).execute();

希望有所帮助