1

我尝试在设备上运行我的 android 应用程序,但我的登录崩溃了。logcat 显示此错误

09-12 21:32:12.289: E/AudioHardwareALSA(149): RE-OPEN AFTER STANDBY:: took 115 msecs
09-12 21:32:12.319: E/AndroidRuntime(4760): FATAL EXCEPTION: main
09-12 21:32:12.319: E/AndroidRuntime(4760): android.os.NetworkOnMainThreadException
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.stts.sparetimetradingsystem.library.JSONParser.getJSONFromUrl(JSONParser.java:44)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.stts.sparetimetradingsystem.library.UserFunctions.loginUser(UserFunctions.java:40)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.stts.sparetimetradingsystem.LoginActivity$Login$1.run(LoginActivity.java:125)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.Handler.handleCallback(Handler.java:605)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.Looper.loop(Looper.java:137)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.app.ActivityThread.main(ActivityThread.java:4424)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.lang.reflect.Method.invokeNative(Native Method)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.lang.reflect.Method.invoke(Method.java:511)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at dalvik.system.NativeStart.main(Native Method)

我哪里做错了?

编辑

这是我在异步任务中的登录代码,我可以知道我的异步任务是否正确编码:

// Background ASYNC Task to login by making HTTP Request
class Login extends AsyncTask<String, String, String> {

    // Before starting background thread Show Progress Dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Authenticating...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    // Checking login in background
    protected String doInBackground(String... params) {
        runOnUiThread(new Runnable() {
            public void run() {

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

            }
        });
        return null;
    }

    // After completing background task Dismiss the progress dialog
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
        if (validUser == true) {
            loginErrorMsg.setText("");
            // Launch HomePage Screen
            Intent homepage = new Intent(getApplicationContext(),
                    HomepageActivity.class);

            // Close all views before launching HomePage
            homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(homepage);

            // Close Login Screen
            finish();
        }
    }
}
4

2 回答 2

2

从 android 3.0(Honeycomb) 开始,Android 不允许在主线程上进行网络调用。所以你必须使用 Asynctask 进行网络调用。

要摆脱这种情况,您需要使用 AsynTask 进行网络调用。

于 2012-09-12T13:36:56.443 回答
2

您正在使用 AsyncTask,但在 doInBackground 中,您实际上是通过以下方式执行网络代码:

 runOnUiThread(new Runnable() { }

这就是您最终遇到此异常的原因,您需要在没有它的情况下执行您的网络代码。我猜你这样做是为了引用应用程序上下文,但是通过 AsyncTask 构造函数提供它相当简单。

于 2012-09-12T13:43:42.277 回答