-1

나는 서버에서 데이터를 액세스하고 가져 오는 응용 프로그램을 만들므로 응용 프로그램이 제대로 작동하고 GingerBread (2.3.5)에서 예상대로 실행되지만 JellyBeans에서 충돌합니다 (4.1.2). 그것은 다음과 같은 오류를 발생2.3.5에서 실행 중이지만 4.1.2에서 충돌하는 Android 응용 프로그램

12-19 14:46:12.027: I/System.out(10088): Domain has been set 

12-19 14:46:12.082: I/System.out(10088): Created http client 

12-19 14:46:12.093: I/System.out(10088): Created the httppost domain 

12-19 14:46:12.097: I/System.out(10088): Response has been initalized by null 

12-19 14:46:12.101: I/System.out(10088): Added the parameter email 

12-19 14:46:12.101: I/System.out(10088): Added the parameter Password 

12-19 14:46:12.136: I/System.out(10088): Setting the entity 

12-19 14:46:12.218: D/AndroidRuntime(10088): Shutting down VM 

12-19 14:46:12.218: W/dalvikvm(10088): threadid=1: thread exiting with uncaught exception (group=0x40ca4300) 

12-19 14:46:12.257: E/AndroidRuntime(10088): FATAL EXCEPTION: main 

12-19 14:46:12.257: E/AndroidRuntime(10088): android.os.NetworkOnMainThreadException 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at java.net.InetAddress.getAllByName(InetAddress.java:214) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at com.yousaf.naveed.CommunicationClass.trydata(CommunicationClass.java:96) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at com.yousaf.naveed.signin.senddata(signin.java:86) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at com.yousaf.naveed.signin$1.onClick(signin.java:57) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.view.View.performClick(View.java:4084) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.view.View$PerformClick.run(View.java:16966) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.Handler.handleCallback(Handler.java:615) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.Handler.dispatchMessage(Handler.java:92) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.Looper.loop(Looper.java:137) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at android.app.ActivityThread.main(ActivityThread.java:4745) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at java.lang.reflect.Method.invokeNative(Native Method) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at java.lang.reflect.Method.invoke(Method.java:511) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 

12-19 14:46:12.257: E/AndroidRuntime(10088): at dalvik.system.NativeStart.main(Native Method) 

12-19 14:46:12.285: W/ActivityManager(248): Force finishing activity com.yousaf.naveed/.signin 

12-19 14:46:12.820: W/ActivityManager(248): Activity pause timeout for ActivityRecord{41479970 com.yousaf.naveed/.signin} 

로그인 완료에 대한 코드는 통신 클래스의 코드는

public void setreader(){ 
    try { 
     reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent(), "UTF-8")); 
     System.out.println("Setting the contents of the Reader"); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     System.out.println("In the UnsupportedEncodingException catch of the Reader"); 
     e.printStackTrace(); 
    } catch (IllegalStateException e) { 
     // TODO Auto-generated catch block 
     System.out.println("In the IllegalStateException catch of the Reader"); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     System.out.println("In the IOException catch of the Reader"); 
     e.printStackTrace(); 
    } 

} 
public void startpost(String str){ 
    datapost=new HttpPost(str); 
    System.out.println("Created the httppost domain"); 
} 
public void insertdata(String tag,String value){ 
    namevaluepairs.add(new BasicNameValuePair(tag,value)); 
    System.out.println("Added the parameter "+tag); 
} 

public void trydata(){ 
    try { 
     this.datapost.setEntity(new UrlEncodedFormEntity(this.namevaluepairs)); 
     System.out.println("Setting the entity"); 

     try { 
      //HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
      this.response = this.client.execute(this.datapost); 
      System.out.println("executing the client"); 
      if(this.response != null){ 
       System.out.println("i am in if of this.response!=null"); 
      } 
      else{ 
       System.out.println("i am in else of this.response!=null"); 
      } 
      System.out.println("in response try box"); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      System.out.println("in ClientProtocolException Catch box"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      System.out.println("in IOException Catch box"); 
      e.printStackTrace(); 
     } 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     System.out.println("in UnSupported Catch box"); 
     e.printStackTrace(); 
    } 
} 
public void readresponse(){  



    try { 
     for (String line = null; (line = reader.readLine()) != null;) { 
      builder.append(line).append("\n"); 

     } 
     System.out.println(this.builder); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    tokener = new JSONTokener(builder.toString()); 
    try { 
     finalResult = new JSONObject(tokener); 
     System.out.println("I am in try block of json final result reading"); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     System.out.println("I catch block of jsonException"); 
     e.printStackTrace(); 
    } 
} 

다음과 같다

protected void senddata() { 
    int status = 0,role=0; 
    int active=0; 
    // TODO Auto-generated method stub 
    @SuppressWarnings("unused") 
    String JSONString = null; 
    ccobj = new CommunicationClass(); 
    ccobj.setDomain("http://naveedyousaf.com/fyp/cakephp-master/cakephp-master/Users/signin"); 
    ccobj.setClient(); 
    ccobj.startpost(ccobj.Domain); 
    ccobj.setResponse(); 
    ccobj.insertdata("email", email); 
    ccobj.insertdata("Password", password); 
    ccobj.trydata(); 
    ccobj.setreader(); 
    ccobj.setStringBuilder(); 
    ccobj.readresponse(); 
    JSONString = new String(ccobj.builder); 

     String first_name = null,last_name = null,emails=null,password=null,emer=null; 
     try { 
      status = ccobj.finalResult.getInt("status"); 
      first_name = ccobj.finalResult.getString("First_Name"); 
      last_name = ccobj.finalResult.getString("Last_Name"); 
      emails = ccobj.finalResult.getString("Email"); 
      password = ccobj.finalResult.getString("Password"); 
      role = ccobj.finalResult.getInt("Role"); 
      //active = ccobj.finalResult.getInt("Active"); 
      ids = ccobj.finalResult.getInt("Id"); 
      System.out.print("============="+ids); 
      emer = ccobj.finalResult.getString("Emergency"); 

     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      System.out.println("In the issue itself"); 
      e.printStackTrace(); 
     } 
     error=(TextView) this.findViewById(R.id.error); 
     System.out.println(status); 
     if(status==2){ 
      try{ 
       error.setTextColor(Color.RED); 
       error.setText("Unrecognized Email"); 
       error.setTextSize(12); 
       fpass.setTextColor(Color.RED); 
       fpass.setTextSize(12); 
       //pd.cancel(); 
      } 
      catch(NullPointerException e){ 
       System.out.println("This is the uncaught exception"); 
      } 

      //error.text.setTextColor(Color.rgb(200,0,0)); 
     } 
     if(status==1){ 
      dcobj = new DataClass(); 
      //ids = Integer.parseInt(id); 
      dcobj.setFirstName(first_name); 
      dcobj.setLastName(last_name); 
      dcobj.setEmail(emails); 
      dcobj.setPassword(password); 
      dcobj.setRole(role); 
      dcobj.setStatus(status); 
      dcobj.setActive(active); 
      dcobj.setId(ids); 
      dcobj.setEmer(emer); 
      sendnewdata(); 
     } 

} 

으로 자사의 매니페스트 파일은 다음 권한을 가진

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

누구든지 왜 예외가 처리되지 않는지 충돌 설명 할 수 있습니다.

로그인의 주된 활동이 있지만이 로그인 클래스는 CommunicationClass를 호출합니다.이 클래스는 postclient 메소드를 사용하여 httpclient 프로토콜을 실행합니다. signin은 httpclient 자체를 실행하지 않지만 실행을 기다리고 있습니다. 비동기 작업.

+0

android.os.NetworkOnMainThreadException –

답변

2

백그라운드 스레드에서 네트워크 작업을 수행하거나 현재처럼 당신이에서 호출하는 기능을하는 모른다 (senddata를 호출 StrictMode

를 대신하지 않도록,하지만 기능은 UI에서 실행 처음에 언급 한 바와 같이

someFunctionOnTheUIThread() 
    { 
    //senddata(); //this is your current senddata() call. Replace it with the following 

    (new AsyncTask<Void, Void, Void>() { 

     @Override 
     protected Void doInBackground(Void... params) { 
      senddata(); 
      return null; 
     } 
    }).execute((Void)null); 
    } 

, 당신은 또한 StrictMode을 해제 할 수 있지만, 매우는 UI를 차단하는 것입니다, 당신은 ANR 수를 얻을 수 있습니다 권장되지이다 : 스레드),이 같은 AsyncTask에 전화하려고 (응용 프로그램 응답 없음 ding) 네트워크가 느릴 때 (또는 요청이 "멈춤"- 양호한 네트워크에서도 발생할 수 있으며 요청할 경우 기본 요청 시간 제한은 AFAIK이며 사용자가 변경하지 않은 것으로 가정하면 30 초).

StackOverflow에서이 질문에 대한 다른 질문을보십시오. 이에 대한 유용하고 자세한 답변이 많이 있습니다. 또한 향후 질문을 위해 으로 보내주십시오. 게시하기 전에 다른 사람이 질문을 이미 받았는지 확인하십시오. 그것은 중복 질문의 양을 낮추고 그것은 다운 - 투표 (그리고 귀하의 질문을 닫고 중복으로 표시) 얻을하지 않습니다.

0
at android.os.StrictMode$AndroidBlockGuardPolicy. 

엄격 모드를 사용하도록 설정했습니다. 비활성화하거나 별도의 스레드에서 네트워크 작업을 수행하십시오.

0

UI 스레드의 네트워크 요청은 android 4.0 이상에서 허용되지 않습니다. 새 스레드를 만들어야합니다.

관련 문제