android.os.NetworkOnMainThreadException

时间:2014-03-21 10:55:40

标签: android android-asynctask

我在代码中使用了asynctask。但是它显示了我在logcat中给出的错误。我创建了一个api 18.in的google api模拟器,它不能正常工作。但是在api8中工作。它是否适用于任何版本的真实设备?

btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                new LoginTask_1().execute();
            }
        });

的AsyncTask

class LoginTask_1 extends AsyncTask<String, String, String> {

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

        /**
         * Deleting product
         * */
        protected String doInBackground(String... args) {
            runOnUiThread(new Runnable() {
                public void run() {
                    String code = inputcode.getText().toString();
                    UserFunctions userFunction = new UserFunctions();
                    Log.d("Button", "Login");
                    JSONObject json = userFunction.loginUser1(id,code);

                    // check for login response
                    try {
                        if (json.getString(KEY_SUCCESS) != null) {
                            loginErrorMsg1.setText("");
                            String res = json.getString(KEY_SUCCESS); 
                            if(Integer.parseInt(res) == 1){
                                DatabaseHandler1 db = new DatabaseHandler1(getApplicationContext());
                                db.addUser(adduser1, adduser2,id, adduser3,adduser4);

                                // Launch Dashboard Screen
                                Intent dashboard = new Intent(getApplicationContext(), MainActivity.class);
                                dashboard.putExtra("name", id);
                                dashboard.putExtra("email", adduser4);
                                //dashboard.putExtra(EXTRA_MESSAGE, id);
                                // Close all views before launching Dashboard
                                dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(dashboard);

                                // Close Login Screen
                                finish();
                                }

                            /*else if(Integer.parseInt(res) == 2){

                                loginErrorMsg.setText("Already logged in");
                            }*/
                            else{
                                // Error in login
                                loginErrorMsg1.setText("Invalid Code");
                            }
                        }
                    } 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 product deleted
            pDialog.dismiss();

        }

    }

logcat的

03-21 06:47:54.403: E/AndroidRuntime(3265): FATAL EXCEPTION: main
03-21 06:47:54.403: E/AndroidRuntime(3265): android.os.NetworkOnMainThreadException
03-21 06:47:54.403: E/AndroidRuntime(3265):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at com.androidhive.pushnotifications.JSONParser.getJSONFromUrl(JSONParser.java:47)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at com.androidhive.pushnotifications.UserFunctions.loginUser(UserFunctions.java:46)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at com.androidhive.pushnotifications.LoginActivity$LoginTask$1.run(LoginActivity.java:125)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at android.os.Handler.handleCallback(Handler.java:730)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at android.os.Looper.loop(Looper.java:137)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at java.lang.reflect.Method.invokeNative(Native Method)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at java.lang.reflect.Method.invoke(Method.java:525)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-21 06:47:54.403: E/AndroidRuntime(3265):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

删除runOnUiThread

runOnUiThread(new Runnable() {
            public void run() {

在后台线程上调用您的doInbackground。您不需要runOnUiThread来执行网络操作。

并在doInbackground中的onPostExecute和startActivity中返回结果。

编辑:

正如onPostExecutedoInbackground而不是 loginErrorMsg1.setText("Invalid Code"); 中的繁荣k upadate ui所暗示的那样

doInbackground

此外,您可以从Activity中的EditText获取文本,并将字符串传递给 btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String code = inputcode.getText().toString(); new LoginTask_1().execute(code); } });

   protected String doInBackground(String... args) {
   String value = args[0];  

然后

{{1}}