This question already has answers here:
How to fix 'android.os.NetworkOnMainThreadException'?
                                
                                    (56个答案)
                                
                        
                                6年前关闭。
            
                    
我开发了一个代码以使用android,Json ans Mysql登录,我的代码在模拟器(android 2.1)中工作,但在智能手机(4.1)中崩溃,这是日志猫中的错误

error in http connection android.os.networkonmainthreadexception


这是我的代码,如果有人可以帮助我更改某些内容,以允许我的应用程序运行到所有android版本中,请先感谢。

public class ConnexionmysqlActivity extends Activity {

        private static final String strURL = "http://mercure.comze.com/mercure/logi.php";
    //  private String result ;
        private Button connexion ;
        private EditText Logon ;
        private EditText password ;
        private JSONArray   jArray;
        private JSONObject  json_data;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            Button connexion = (Button) findViewById(R.id.btn);
            final EditText Logon = (EditText) findViewById(R.id.login);
            final EditText password = (EditText) findViewById(R.id.mdpt);


            connexion.setOnClickListener(new View.OnClickListener() {

                @SuppressWarnings("unused")
                public void onClick(View v) {
                    String result =null;
                    InputStream is = null;
                    StringBuilder sb = new StringBuilder();
                    ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair> ();
                    nameValuePairs.add(new BasicNameValuePair("user",Logon.getText().toString()));

                    try{

                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(strURL);
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();
                    }catch(Exception e){
                        Log.e("log_tag", "Error in http connection " + e.toString());
                    }
                    try{
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");

                        }
                        is.close();
                        result=sb.toString();

                    }catch(Exception e){
                        Log.e("log_tag", "Error in http connection " + e.toString());
                    }
                    String essai=result.substring(0, 4) ;
                    try {
                        if (result.matches("<br >")){
                             essai=result.substring(0, 2) ;
                        }
                        JSONArray jArray = new JSONArray(result);
                        int b=jArray.length();



                           JSONObject json_data = jArray.getJSONObject(0);


                           String mot_pass =    json_data.getString("mdp").toString();
                           String login =   json_data.getString("login").toString();
                           if (mot_pass.equals(password.getText().toString()) ){

                               Intent principale =new Intent(ConnexionmysqlActivity.this,compte.class);
                               principale.putExtra("login",login);
                               startActivity(principale);

                           }
                           else {

                               Toast.makeText(ConnexionmysqlActivity.this, "mot de pass invalide ", Toast.LENGTH_LONG).show();
                           }


                   }catch(JSONException e){
                     //  Log.e("log_tag", "Error parsing data " + e.toString());
                       Toast.makeText(ConnexionmysqlActivity.this, "Utilisateur Inexistant ", Toast.LENGTH_LONG).show();
                   }

                }
                });

        }
    }


编辑:我在我的代码中做了一些更改(使用asyncTask),但是这次我的代码也无法正常工作,这是我所做的更改:

public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            Button connexion = (Button) findViewById(R.id.btn);
            final EditText Logon = (EditText) findViewById(R.id.login);
            final EditText password = (EditText) findViewById(R.id.mdpt);


            connexion.setOnClickListener(new View.OnClickListener() {

                @SuppressWarnings("unused")
                public void onClick(View v) {


                    new callServiceTask().execute();

                }
                });

        }

            class callServiceTask extends AsyncTask<Void, Void, Void>
            {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(ConnexionmysqlActivity.this);
                    pDialog.setMessage("Loading...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }
                @Override
                protected Void doInBackground(Void... params) {

                    // call web service
                     ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair> ();
                        nameValuePairs.add(new BasicNameValuePair("user",Logon.getText().toString()));

                        try{

                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost(strURL);
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();
                        }catch(Exception e){
                            Log.e("log_tag", "Error in http connection " + e.toString());
                        }
                        try{
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");

                            }
                            is.close();
                            result=sb.toString();

                        }catch(Exception e){
                            Log.e("log_tag", "Error in http connection " + e.toString());
                        }
                        String essai=result.substring(0, 4) ;
                        try {
                            if (result.matches("<br >")){
                                 essai=result.substring(0, 2) ;
                            }
                            JSONArray jArray = new JSONArray(result);
                            int b=jArray.length();



                               JSONObject json_data = jArray.getJSONObject(0);


                               String mot_pass =    json_data.getString("mdp").toString();
                               String login =   json_data.getString("login").toString();
                               if (mot_pass.equals(password.getText().toString()) ){

                                   Intent principale =new Intent(ConnexionmysqlActivity.this,compte.class);
                                   principale.putExtra("login",login);
                                   startActivity(principale);

                               }
                               else {

                                   Toast.makeText(ConnexionmysqlActivity.this, "mot de pass invalide ", Toast.LENGTH_LONG).show();
                               }


                       }catch(JSONException e){
                         //  Log.e("log_tag", "Error parsing data " + e.toString());
                           Toast.makeText(ConnexionmysqlActivity.this, "Utilisateur Inexistant ", Toast.LENGTH_LONG).show();
                       }
                    return null;
                }

                @Override
                protected void onPostExecute(Void resulta) {

                    //bind data in lisview or any other componet
             pDialog.dismiss();
                    super.onPostExecute(resulta);
                }

            }


日志猫:

07-23 08:16:53.028: W/dalvikvm(15420): threadid=11: thread exiting with uncaught exception (group=0x2b542210)
07-23 08:16:53.048: E/AndroidRuntime(15420): FATAL EXCEPTION: AsyncTask #1
07-23 08:16:53.048: E/AndroidRuntime(15420): java.lang.RuntimeException: An error occured while executing doInBackground()
07-23 08:16:53.048: E/AndroidRuntime(15420):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.lang.Thread.run(Thread.java:856)
07-23 08:16:53.048: E/AndroidRuntime(15420): Caused by: java.lang.NullPointerException
07-23 08:16:53.048: E/AndroidRuntime(15420):    at com.project.mercureproject.ConnexionmysqlActivity$callServiceTask.doInBackground(ConnexionmysqlActivity.java:98)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at com.project.mercureproject.ConnexionmysqlActivity$callServiceTask.doInBackground(ConnexionmysqlActivity.java:1)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-23 08:16:53.048: E/AndroidRuntime(15420):    ... 5 more

最佳答案

将此代码添加到oncreate方法中:

StrictMode.ThreadPolicy策略=新的StrictMode.ThreadPolicy.Builder()。permitAll()。build();
StrictMode.setThreadPolicy(policy);

09-03 17:28