应用程序工作在模拟器,但它不能在智能手机工作 [英] App works on emulator but it doesn't work on Smartphone

查看:289
本文介绍了应用程序工作在模拟器,但它不能在智能手机工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序适用于模拟器不错,但是当我在我的智能手机(银河S3)后,我出口崩溃的此活动,运行它哪里有HTTP连接!哪里有问题?在code或出口?当我点击按钮,它崩溃的连接。

 公共类扩展登录活动{@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.login);
    最终所有MyApplication的MyApp =(所有MyApplication)this.getApplication();    ViewGroup中布局=(ViewGroup中)findViewById(R.id.login);
    MyApp.changeFonts(布局);    如果(!MyApp.IsConnect())
       {Toast.makeText(getBaseContext(),CONNESSIONE非disponibile,Toast.LENGTH_SHORT).show();}
    最终按钮FER =(按钮)findViewById(R.id.invia);
    fer.setOnClickListener(新OnClickListener(){        @覆盖
        公共无效的onClick(查看为arg0){
            字符串URL =htt​​p://corraphp.altervista.org/server.php;
            的EditText txtNome =(EditText上)findViewById(R.id.txtNome);
            的EditText txtTessera =(EditText上)findViewById(R.id.txtCodice);            。字符串cognome = txtNome.getText()的toString();
            。字符串Tessera公司= txtTessera.getText()的toString();            ArrayList的<&的NameValuePair GT;对=新的ArrayList<&的NameValuePair GT;();
            pairs.add(新BasicNameValuePair(cognome,cognome));
            pairs.add(新BasicNameValuePair(Tessera公司,Tessera公司));
            如果((cognome.equals())及及(tessera.equals()))
            {Toast.makeText(getBaseContext(),别名选择IL cognomeê拉Tessera公司,Toast.LENGTH_LONG).show();返回;}
            其他
            {
            如果(cognome.equals())
            {Toast.makeText(getBaseContext(),别名选择IL cognome,Toast.LENGTH_LONG).show();返回;}
            如果(tessera.equals())
            {Toast.makeText(getBaseContext(),别名选择拉Tessera公司,Toast.LENGTH_LONG).show();返回;}
            }
            InputStream为= NULL;
            StringBuilder的SB = NULL;
            字符串结果= NULL;            // HTTP POST
            尝试{
                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpPost httppost =新HttpPost(URL);
                httppost.setEntity(新UrlEn codedFormEntity(对));
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();
                是= entity.getContent();
            }赶上(例外五){
                Log.e(log_tag,在HTTP连接错误+ e.toString());
            }            //响应转换为字符串
            尝试{
                读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
                SB =新的StringBuilder();
                sb.append(reader.readLine()+\\ n);
                串行=0;                而((行= reader.readLine())!= NULL){
                    sb.append(行+\\ n);
                }                is.close();
                结果= sb.toString();            }赶上(例外五){
                Log.e(log_tag,错误转换结果+ e.toString());
            }            //配对数据
            尝试{
            JSONArray jArray =新JSONArray(结果);
            JSONObject的json_data = NULL;
            INT标识= 0;
            串Cognome =;
            的for(int i = 0; I< jArray.length();我++){
                    json_data = jArray.getJSONObject(ⅰ);
                    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公司);
            意图I =新意图(login.this,saluto.class);
            startActivity(ⅰ);
            完();
            }赶上(JSONException E1){
                  AlertDialog.Builder alertDialogBu​​ilder =新AlertDialog.Builder(login.this);
                     alertDialogBu​​ilder.setTitle(错误);
                     alertDialogBu​​ilder.setMessage(Cognome / Tessera公司errati);                     alertDialogBu​​ilder.setNeutralButton(OK,新DialogInterface.OnClickListener(){
                            公共无效的onClick(DialogInterface对话,诠释的id){
                                dialog.cancel();                            }
                        });
                     AlertDialog alertDialog = alertDialogBu​​ilder.create();
                     //显示警报
                     alertDialog.show();            }赶上(ParseException的E1){
                e1.printStackTrace();
            }
        }
    });}}


解决方案

从code,似乎网络运行是onClickListener内,应用程序的UI线程/主线程访问。

检查O.S.版本的仿真器和设备:

为什么你的应用程序会崩溃在Android 3.0及以上版本,但会很好地工作在Android 2.x的原因是因为Honeycomb和Ice Cream Sandwich的(及以后​​)的O.S.是关于对UI线程滥用严格得多。例如,在Android设备上运行蜂窝状或以上时,检测到UI线程上的网络连接, NetworkOnMainThreadException 将被抛出:

  E / AndroidRuntime(673):了java.lang.RuntimeException:无法启动活动
    ComponentInfo {com。示例/ com.example.ExampleActivity}:android.os.NetworkOnMainThreadException

的解释,为什么出现这种情况是有据可查的 Android开发者的网站


  

A NetworkOnMainThreadException 被抛出时,应用程序
  尝试在它的主线程执行联网操作。这是
  只抛出应用针对蜂窝SDK或更高版本。
  针对应用较早的SDK版本都可以做
  网络对他们的主事件循环线程,但它的高度
  气馁。


去走遍:

为什么应用程序会崩溃或工作依赖于OS

尽量的AsyncTask避免NetworkOnMainThread

为什么您不要使用严格模式选择,因为你的解决方案,只是为了调试(我建议避免这种情况也确实,你知道什么是现在的问题):结果
<一href=\"http://stackoverflow.com/questions/18297485/android-os-networkonmainthreadexception-sending-an-email-from-android/18297516#18297516\">Critical解决它,而不是通过设置主题策略

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

解决方案

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

这篇关于应用程序工作在模拟器,但它不能在智能手机工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆