我不知道如何解决(android.os.networkonmainthreadexception) [英] I dont know how to solve (android.os.networkonmainthreadexception)

查看:163
本文介绍了我不知道如何解决(android.os.networkonmainthreadexception)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是得到这个错误

 公共类FlightAvailabityGoActivity扩展ListActivity {
的String [] MONTHNAME = {一月,二月,
          月,月,月,君,七月,
          月,月,月,月,
          月
          };


日期userDate =新的日期();
INT DepDay = userDate.getDays();
INT DepMonth = userDate.getMonths();

豆beanz =新豆();
私人TextView的fromToTextView;
台历挂历=新的GregorianCalendar();
  字符串AM_PM;
  字符串变量=从
  从给私人TextView的;
  语言LANG =新的语言();
  串En_Ar = lang.getLang();
  元素DEST;

  / **第一次创建活动时调用。 * /
  @覆盖
  公共无效的onCreate(包savedInstanceState){

    尝试{
    Log.v(TAG,在走活动+ TAG);

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    的setContentView(R.layout.listplaceholder_flightavailabity);
    如果(En_Ar.equals(阿拉伯​​语))
    {
    。getWindow()setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.window_title_flightavailabity_ar);
   //从=(TextView中)findViewById(R.id.fromText);
   // from.setText(من);
   //为=(TextView的)findViewById(R.id.toText);
    //to.setText(إلى);
    Log.v(TAG,1+ TAG);
    }
    其他
    {
          Log.v(TAG,1+ TAG);
    getWindow()。setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
     R.layout.window_title_flightavailabity);
    }






    ////
    捆绑额外= getIntent()getExtras()。

    字符串FromCity = extras.getString(从);
    串ToCity = extras.getString(发送);
    Log.v(TAG,从一个城市搬家后+ FromCity);
    Log.v(TAG,城市运行后+ ToCity);






    ArrayList的< HashMap的<字符串,字符串>> mylist中=新的ArrayList< HashMap的<字符串,字符串>>();
    ArrayList的< HashMap的<字符串,字符串>> mylist1 =新的ArrayList< HashMap的<字符串,字符串>>();

    Log.v(TAG,2+ TAG);
    // XML字符串= XMLfunctions.getXMLFlightAva(FromCity,ToCity);
    XML字符串= XMLfunctions.getXMLFlightAva(FromCity,ToCity); //错误是在这里
    Log.v(TAG,3+ TAG); //这将不显示
    XML = xml.trim();
    Log.v(TAG,4+ TAG);
 

我红呢,我理解它如何使用互联网,但我不知道该如何解决呢? 你可以看到我在我的XML功能类读取XML通过HTTP GET和它的字符串返回XML在这些地方的每一件事崩溃

我必须改变类                XML字符串= XMLfunctions.getXMLFlightInfo(FromCity);

其相同的方法

  XML字符串= XMLfunctions.getXMLFlightAva(FromCity,ToCity);
 

这是类

 公共类XMLfunctions {
             字符串标记;



公共最后静态文件XMLfromString(XML字符串){


    文档DOC = NULL;

    DocumentBuilderFactory的DBF = DocumentBuilderFactory.newInstance();
    尝试 {

        DocumentBuilder的DB = dbf.newDocumentBuilder();

        InputSource的是=新的InputSource();
        is.setCharacterStream(新StringReader(XML));
        DOC = db.parse(是);

    }赶上(的ParserConfigurationException E){
        的System.out.println(XML解析错误:+ e.getMessage());
        返回null;
    }赶上(的SAXException E){
        的System.out.println(错的XML文件的结构:+ e.getMessage());
        返回null;
    }赶上(IOException异常E){
        的System.out.println(I / O exeption:+ e.getMessage());
        返回null;
    }

    返回文档;

}

/ **返回元素值
  *参数ELEM元素(这是XML标记)
  返回:元素的值,否则空字符串
  * /
 公共最后静态字符串getElementValue(节点ELEM){
     节点的孩子;
     如果(ELEM!= NULL){
         如果(elem.hasChildNodes()){
             对于(孩子= elem.getFirstChild();!小子= NULL;孩子= kid.getNextSibling()){
                 如果(kid.getNodeType()== Node.TEXT_NODE){
                     返回kid.getNodeValue();
                 }
             }
         }
     }
     返回 ;
 }
 ////////////////////////
 公共静态字符串getXMLFlightInfo(字符串Y_or_T){
        串线= NULL;
        字符串变量=TAG;
        日期userDate =新的日期();
        INT DepDay = userDate.getDays();
        INT DepMonth = userDate.getMonths();



        尝试 {

            DefaultHttpClient的HttpClient =新DefaultHttpClient();
        // HttpPost httpPost =新HttpPost(http://p-xr.com/xml);
            // HTTPGET httpPost =新HttpGet("http://10.128.11.206:9080/mobile/FlightSchdIphoneServlet?depCity="+fromCity+"&arrCity="+toCity+"&day="+DepDay+"&month="+DepMonth+"");
            // HTTPGET httpPost =新HttpGet("http://mysv.net.sa/Web/mobile/FlightAvailIphoneServlet?depCity=JED&arrCity=RUH&day=29&month=11&submit=+GO+");
            HTTPGET httpPost =新HTTPGET(http://10.131.13.43:9080/onlineSMS/xmlFlightInfo.html);

            HTT presponse HTT presponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = HTT presponse.getEntity();
            行= EntityUtils.toString(httpEntity);



        }赶上(UnsupportedEncodingException E){
            行=<阵列状态= \错误\><味精>无法连接到服务器16; /味精>< /阵列>中;
        }赶上(MalformedURLException异常E){
            行=<阵列状态= \错误\><味精>无法连接到服务器16; /味精>< /阵列>中;
        }赶上(IOException异常E){
            行=<阵列状态= \错误\><味精>无法连接到服务器16; /味精>< /阵列>中;
        }

        回线;

}
 

解决方案

由于API等级9 StrictMode.ThreadPolicy 介绍并默认行为已经在API级别11,这在短,不允许网络操作被改变(包括HttpClient的和HttpURLConnection类)UI线程上被执行。

正确的战略是移动网络运营关闭UI线程,例如使用的AsyncTask

希望这种帮助。

I always get this error

   public class FlightAvailabityGoActivity extends ListActivity {
String[] monthName = {"Jan", "Feb",
          "Mar", "Apr", "May", "Jun", "Jul",
          "Aug", "Sep", "Oct", "Nov",
          "Dec"
          };


date userDate=new date();
int DepDay=userDate.getDays();
int DepMonth=userDate.getMonths();

bean beanz=new bean();
private TextView fromToTextView;
Calendar calendar = new GregorianCalendar();
  String am_pm;
  String TAG="from";
  private TextView from,to;
  languages lang=new languages();
  String En_Ar=lang.getLang();
  Element dest;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    try{
    Log.v(TAG, "in go activity       " +TAG);

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.listplaceholder_flightavailabity);
    if(En_Ar.equals("arabic"))
    {
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title_flightavailabity_ar);
   // from=(TextView)findViewById(R.id.fromText);
   // from.setText("  من  ");
   // to=(TextView)findViewById(R.id.toText);
    //to.setText("  إلى  ");
    Log.v(TAG, "1       " +TAG);
    }
    else
    {
          Log.v(TAG, "1       " +TAG);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,  
     R.layout.window_title_flightavailabity);
    }






    ////
    Bundle extras = getIntent().getExtras();

    String FromCity = extras.getString("from");
    String ToCity = extras.getString("to");
    Log.v(TAG, "from city after moving   " +FromCity);
    Log.v(TAG, "to city after moving   " +ToCity);






    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String, String>> mylist1 = new ArrayList<HashMap<String, String>>();

    Log.v(TAG, "2       " +TAG);
    //String xml = XMLfunctions.getXMLFlightAva(FromCity,ToCity);
    String xml=XMLfunctions.getXMLFlightAva(FromCity,ToCity);  // error is here
    Log.v(TAG, "3      " +TAG);  // this will not display
    xml=xml.trim();
    Log.v(TAG, "4       " +TAG);

I red about it and I understand its about using internet but I don't know how to solve it? as you can see I read XML by HTTP get in my XML function class and it returns XML in string here where every thing crashed

Do I have to change the class in String xml=XMLfunctions.getXMLFlightInfo(FromCity);

its the same method as

          String xml=XMLfunctions.getXMLFlightAva(FromCity,ToCity);

this is the class

             public class XMLfunctions {
             String TAG;



public final static Document XMLfromString(String xml){


    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}

/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }
 ////////////////////////
 public static String getXMLFlightInfo(String Y_or_T){   
        String line = null;
        String TAG="TAG";
        date userDate=new date();
        int DepDay=userDate.getDays();
        int DepMonth=userDate.getMonths();



        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
        //  HttpPost httpPost = new HttpPost("http://p-xr.com/xml");
            //HttpGet httpPost=new HttpGet("http://10.128.11.206:9080/mobile/FlightSchdIphoneServlet?depCity="+fromCity+"&arrCity="+toCity+"&day="+DepDay+"&month="+DepMonth+"");
            //HttpGet httpPost=new HttpGet("http://mysv.net.sa/Web/mobile/FlightAvailIphoneServlet?depCity=JED&arrCity=RUH&day=29&month=11&submit=+GO+");
            HttpGet httpPost=new HttpGet("http://10.131.13.43:9080/onlineSMS/xmlFlightInfo.html");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);



        } catch (UnsupportedEncodingException e) {
            line = "<array status=\"error\"><msg>Can't connect to server</msg></array>";
        } catch (MalformedURLException e) {
            line = "<array status=\"error\"><msg>Can't connect to server</msg></array>";
        } catch (IOException e) {
            line = "<array status=\"error\"><msg>Can't connect to server</msg></array>";
        }

        return line;

}

解决方案

StrictMode.ThreadPolicy was introduced since API Level 9 and the default behaviour had been changed in API Level 11, which in short, does not allow network operation (include HttpClient and HttpUrlConnection) get executed on UI thread.

The correct strategy is move network operation off the UI thread, for example using AsyncTask.

hope this help.

这篇关于我不知道如何解决(android.os.networkonmainthreadexception)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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