更改minSDKVersion时发生NetworkOnMainThreadException错误

时间:2014-03-24 05:30:09

标签: java android

我已经开发了一个登录和注册系统,当minSDKVersion设置为8时,代码工作正常。但是当我将minSDkVersion更改为更高版本时说11或12时,当我尝试登录或注册时应用程序崩溃。我应该在代码中创建,以便我可以运行更高版本.LogAActivity.java文件如下:

   package com.example.trial;

   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 com.example.trial.library.DatabaseHandler;
   import com.example.trial.library.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();
            Log.d("Button", "Login");
            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();
            }
        }
    });

    // Link to Register Screen
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

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

RegisterActivity.java文件是:

    package com.example.trial;

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

    import com.example.trial.library.DatabaseHandler;
    import com.example.trial.library.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 {
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
    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
            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
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

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

logcat看起来像这样:

   03-24 01:20:22.154: E/AndroidRuntime(1787): FATAL EXCEPTION: main
   03-24 01:20:22.154: E/AndroidRuntime(1787): android.os.NetworkOnMainThreadException
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at libcore.io.IoBridge.connect(IoBridge.java:112)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at java.net.Socket.connect(Socket.java:842)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at com.example.trial.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at com.example.trial.library.UserFunctions.loginUser(UserFunctions.java:43)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at com.example.trial.LoginActivity$1.onClick(LoginActivity.java:56)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.view.View.performClick(View.java:4240)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.view.View$PerformClick.run(View.java:17721)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.os.Handler.handleCallback(Handler.java:730)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.os.Handler.dispatchMessage(Handler.java:92)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.os.Looper.loop(Looper.java:137)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at android.app.ActivityThread.main(ActivityThread.java:5103)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at java.lang.reflect.Method.invokeNative(Native Method)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at java.lang.reflect.Method.invoke(Method.java:525)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
   03-24 01:20:22.154: E/AndroidRuntime(1787):  at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:1)

此处,您无法在api级别11的UI线程上执行网络操作。

因此,你必须使用 AsyncTask 线程

AsyncTask示例。

 class DowloadTest extends AsyncTask<String, Integer, String>

 {
    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(YourActivityName.this);
        pDialog.setMessage("Please wait..");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    };

    @Override
    protected String doInBackground(String... params) {
        // parse your data here
        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        pDialog.dismiss();

        }

    }
}

然后在需要时执行此功能,如

  new DowloadTest().execute();

如需更多参考,请转到Here

答案 1 :(得分:1)

//您可以在异步任务类中添加json代码

  class callservice extends AsyncTask<String, String, String>
  {
    private ProgressDialog pDialog;
    String message = "";
    private String result;

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args)
    {
         // Write your json code which get data

    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url)
    {
        // dismiss the dialog after getting all products
        if (pDialog != null)
            pDialog.dismiss();

    }
}

答案 2 :(得分:1)

Bcoz of your SDK tools are maybe Upgrade version doesnt support.. for example you create your project in SDK min level is 8 but your android SDk version tools is APK level 19 means it may occurs so go to your SDk Folder and delete tools Folder and then Copy your cuurent version of SDk tools must be put it in your SDK Folder.
you are using low level APK version means it will generate this line bcoz you want to access high high level code in Upgrade version supported methods means this lines will shows of your methods..

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {

and also set this line in your activity

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(
                    android.R.integer.config_shortAnimTime);
or 
if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }


thank you.

答案 3 :(得分:0)

我也遇到了同样的问题,对我有用的解决方案是:

如果您不希望在活动中使用AsyncTask,请尝试在LoginActivity.java的onCreate中添加以下代码段

if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

因此,这将节省您解决此错误的时间和精力。

P.S。如果在将这些行添加到您的活动后出现错误,请尝试清理您的应用程序。您也可以尝试添加

@SuppressLint( “NewApi”) 在oncreate方法之前。像这样,

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {

希望这也能帮到你。