1

我收到有关主 UI 线程的错误,我不确定应该将 AsyncTask 类放在此代码中的哪个位置。它应该在 LoginActivity 类、UserFunction 类还是 JSONParser 类中,我还需要帮助弄清楚如何构造 AsyncTask。我一直在尝试许多变化,但我无法弄清楚

谢谢

登录活动类

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();
            }
        }
    });

用户函数类

 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 类

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;

  }
 }
4

2 回答 2

1

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

如果我没记错的话,你getJSONFromUrl只是在做网络操作。所以使用 Asynctask 调用它

于 2013-06-26T03:42:49.127 回答
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();

希望有帮助

于 2013-06-26T04:53:37.347 回答