0

I developed a code to login with android,Json ans Mysql, my code work in the emulator (android 2.1) but it crash in the smartphone (4.1) and this is the error in the log cat

error in http connection android.os.networkonmainthreadexception

This is my code and if someone can help me to change something to allow my application to work into all android version.Thanks in advance.

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();
                   }

                }
                });

        }
    }

Edit :I made some changes in my code (with the asyncTask) but my code dosen't work this time also,this is the changes that I made:

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);
                }

            } 

The logcat :

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
Delgado
  • 216
  • 3
  • 16
  • 1
    You should run your code in an `AsyncTask` to avoid this kind of error as you cannot do network activities on the `MainThread` and `AsyncTask` will take care of making a thread to handle this sort of activity. – kabuto178 Jul 23 '13 at 05:18
  • Thank you for your answers ,I tried to change my code like that (I put the changes into the question ) ..but il still crushing. – Delgado Jul 23 '13 at 06:22

2 Answers2

2

add your oncreate metod this code:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

celebi
  • 21
  • 4
0

You are calling web service on main thread.. so you are getting network on main thread execption.. call webservice in AsyncTask

class callServiceTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {

        // call web service
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

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

} 

and call like this way

 new callServiceTask().execute();
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75