android.os.NetworkOnMainThreadException 正在尝试从 android activity 访问数据库。 Android 工作室

android.os.NetworkOnMainThreadException Trying to access database from android activity. Android Studio

我在登录 Activity 中收到 android.os.NetworkOnMainThreadException。基本上我只是想检查用户输入的用户 ID 和密码是否正确,即是否允许用户登录。我已经搜索了一个解决方案,并且知道该异常与主线程上的网络有关。但我正在使用 AsyncTask。我仍然遇到这个例外。这是我的 LoginActivity.java

    public class LoginActivity extends AppCompatActivity {

    JSONParser jsonParser = new JSONParser();
    // single product url
    private static final String url_user_check_login = "##########################/android_connect/db_connect.php";
     int success=0;
    String id="";
    String password="";
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

//        Defining onClickListener for Login Button
        Button loginBtn=(Button) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Check credentials
                EditText phone=(EditText)findViewById(R.id.phone_txt);
                EditText pwd=(EditText)findViewById(R.id.password_txt);
                id=phone.getText().toString();
                password=pwd.getText().toString();
                new CheckUserLogin().execute();
                if (success == 1) {

                    Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class);
                    startActivity(intent);

                }else{
                    // product with id not found
                }
            }
        });
    }
    class CheckUserLogin extends AsyncTask<String, String, String> {

        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag

                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("id", id));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_user_check_login, "GET", params);

                        // check your log for json response
//                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }


    }
}

我不知道这是否重要,但我尝试调试并在 doInBackground 方法中放置断点,但我的调试器只是忽略了断点,它只是吹过了新的 CheckUserLogin().execute();声明。

这也是我的异常堆栈跟踪。

    FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489)
at com.heycabs.heycabs.JSONParser.makeHttpRequest(JSONParser.java:65)
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.run(LoginActivity.java:98)at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5409)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
at dalvik.system.NativeStart.main(Native Method)

您错误地使用了 Asynktask。 success == 1 永远不会执行,因为同步命令会在纳秒内发生,而网络则需要几毫秒。

在 Asynk 完成时执行 startActivity(intent)....最后你创建了一个新线程,并在其中返回到 UI 一个:

runOnUiThread(new Runnable()

这是不正确的。请阅读有关 AsynkTask. And read this example

的文档