Question

My app works good on emulator, but when i run it on my smartphone (galaxy s3) after i exported it crashes on this activity, where there is HTTP connect! Where is the problem? The code or export? When i click the button for the connection it crashes.

public class login extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    final MyApplication MyApp = (MyApplication) this.getApplication();

    ViewGroup layout = (ViewGroup) findViewById(R.id.login);
    MyApp.changeFonts(layout);

    if (!MyApp.IsConnect())
       {Toast.makeText(getBaseContext(), "Connessione non disponibile", Toast.LENGTH_SHORT).show();}
    final Button fer = (Button) findViewById(R.id.invia);
    fer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String url = "http://corraphp.altervista.org/server.php";
            EditText txtNome = (EditText) findViewById(R.id.txtNome);
            EditText txtTessera = (EditText) findViewById(R.id.txtCodice);

            String cognome = txtNome.getText().toString();
            String tessera = txtTessera.getText().toString();

            ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("cognome",cognome));
            pairs.add(new BasicNameValuePair("tessera", tessera));
            if ((cognome.equals("")) && (tessera.equals("")))
            {Toast.makeText(getBaseContext(), "Inserire il cognome e la tessera", Toast.LENGTH_LONG).show(); return;}
            else
            {
            if (cognome.equals(""))
            { Toast.makeText(getBaseContext(), "Inserire il cognome", Toast.LENGTH_LONG).show(); return;}   
            if  (tessera.equals(""))
            { Toast.makeText(getBaseContext(), "Inserire la tessera", Toast.LENGTH_LONG).show(); return;}
            }
            InputStream is = null;
            StringBuilder sb=null;
            String result=null;

            //http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                httppost.setEntity(new UrlEncodedFormEntity(pairs));
                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());
            }

            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");
                String line="0";

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

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

            }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
            }

            //paring data
            try{
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data=null;
            int id = 0; 
            String Cognome = "";
            for(int i=0;i<jArray.length();i++){
                    json_data = jArray.getJSONObject(i);
                    id = json_data.getInt("id");
                    Cognome = json_data.getString("cognome");
            }

            MyApp.setUtente(json_data.getInt("id"));
            MyApp.setCognome(json_data.getString("cognome"));
            MyApp.setTessera(tessera);
            Intent i = new Intent(login.this, saluto.class);
            startActivity(i);
            finish();
            }catch(JSONException e1){
                  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(login.this);       
                     alertDialogBuilder.setTitle("error");       
                     alertDialogBuilder.setMessage("Cognome / Tessera errati");

                     alertDialogBuilder.setNeutralButton("ok",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                dialog.cancel();

                            }
                        });
                     AlertDialog alertDialog = alertDialogBuilder.create();
                     // show alert  
                     alertDialog.show();

            }catch (ParseException e1){
                e1.printStackTrace();
            }
        }
    });}}
Was it helpful?

Solution

From your code, it seems the network operation is inside the onClickListener, accessed on the UI thread / main thread of the application.

Check O.S. version on emulator and device:

The reason why your application would crash on Android versions 3.0 and above, but would work fine on Android 2.x is because Honeycomb and Ice Cream Sandwich(and onwards), the O.S. are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown:

E/AndroidRuntime(673): java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example/com.example.ExampleActivity}: android.os.NetworkOnMainThreadException

The explanation as to why this occurs is well documented on the Android developer's site:

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

Go through:

Why the app would crash or work depending on O.S.

Try AsyncTask to avoid NetworkOnMainThread

Why should you not use the Strict Mode alternative as your solution and only to debug(i'd suggest avoid that also actually, you know what is the problem now):
Critical to fix it, not by setting Thread policies

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top