应用程序适用于模拟器,但它不适用于智能手机

时间:2014-05-02 16:13:54

标签: android http export emulation device

我的应用程序在模拟器上运行良好,但是当我在我的智能手机上运行它(galaxy s3)后我导出它崩溃了这个活动,那里有HTTP连接!问题出在哪儿?代码还是导出?当我点击连接按钮时,它会崩溃。

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

1 个答案:

答案 0 :(得分:0)

从您的代码中,似乎网络操作位于onClickListener中,可在应用程序的UI线程/主线程上访问。

检查O.S.模拟器和设备上的版本:

您的应用程序在Android 3.0及更高版本上崩溃的原因,但在Android 2.x上运行正常是因为Honeycomb和Ice Cream Sandwich(及以后),O.S。关于滥用UI线程的问题要严厉得多。例如,当运行HoneyComb或更高版本的Android设备检测到UI线程上的网络访问时,将抛出NetworkOnMainThreadException

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

Android developer's site

详细记录了为何发生这种情况的原因
  

应用程序时抛出NetworkOnMainThreadException   尝试在其主线程上执行网络操作。这是   仅针对Honeycomb SDK或更高版本的应用程序抛出。   允许使用早期SDK版本的应用程序   他们的主要事件循环线程上的网络,但它是很重要的   气馁。

通过:

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

Try AsyncTask to avoid NetworkOnMainThread

为什么不使用Strict Mode替代方案作为您的解决方案并且仅用于调试(我建议实际上避免使用它,您现在知道问题是什么):
Critical to fix it, not by setting Thread policies