2014-03-24 2 views
0

다음 Android 코드가 있습니다. Android 앱이 소켓 프로그램에 연결되어 있고 스레드 모델에서 결과가 "성공"으로 표시됩니다. 그 후 경고 대화 상자를 표시하려고 시도하지만 안드로이드 프로그램에서 예외가 발생합니다. thread exiting with uncaught exception 여기서 잘못된 정보를 얻을 수 없습니다. 스레드 내에 경고를 표시 할 수 있습니까? 제발 조언.Android : 소켓 대화 상자 내에서 알림 대화 상자에서 예외가 발생합니다.

public class RandomIDActivity extends Activity { 

     ............. 

     clientthread = new ClientThread(); 

      Button connectBtn = (Button) findViewById(R.id.button2); 
      connectBtn.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 

        Thread t = new Thread(new ClientThread()); 
        t.start(); 
       } 
      }); 

     } 


class ClientThread implements Runnable { 
     @Override 
     public void run() 
     { 
      // We got this IP from servlet and stored temporarily, so retrieve it from there. 
      String socketServerIP = ((GlobalStore) RandomIDActivity.this.getApplication()).getSocketIPAddress(); 
      Log.d("socketServerIP", socketServerIP); 

      try { 
       InetAddress serverAddr = InetAddress.getByName(socketServerIP); 
       socket = new Socket(serverAddr, SERVERPORT); 

       pw = new PrintWriter(socket.getOutputStream(), true); 
       EditText randTxtField = (EditText) findViewById(R.id.editText1); 
       pw.println(randTxtField.getText().toString()); 
       //output.write(imgbyte,0,imgbyte.length); 
       pw.flush();    

       // Read randrom ID returned by Socket 
       BufferedReader socketReader; 
       try { 
        socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        msgStr = socketReader.readLine(); 
        Log.d("msgStr: ", msgStr); 

        if (msgStr.equalsIgnoreCase("SUCCESS")) 
        { 
         socket.close(); 

       // Crashing if I call alert dialog like this. 
         CobrowseAlertDialog("Successfully connected! Click OK to starts screen sharing!", true); 

         //Intent intent = new Intent(context, MainActivity.class); 
         //startActivity(intent); 
        } 
        else 
        { 
         CobrowseAlertDialog("There seems to be problem in connecting..Try connecting it again with proper Random Auth ID!", false); 
        } 

       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 
      catch (UnknownHostException e1) { 
       e1.printStackTrace(); 
      } 
      catch (IOException e1) { 
       e1.printStackTrace(); 
      } 

     } 
    } 


    public void CobrowseAlertDialog(String msg, boolean bMove) { 

      AlertDialog.Builder builder = new AlertDialog.Builder(RandomIDActivity.this); // getParent() 
      builder.setTitle("Cobrowsing") 
      .setMessage(msg) 
      .setCancelable(false) 
      .setNegativeButton("Ok",new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        dialog.cancel(); 

        //Intent intent = new Intent(context, MainActivity.class); 
        //startActivity(intent); 
       } 
      }); 
      AlertDialog alert = builder.create(); 
      alert.show(); 
     } 

    } 

로그 캣 :

03-24 17:12:20.353: D/socketServerIP(32717): 192.168.1.21 
03-24 17:12:20.503: D/msgStr:(32717): SUCCESS 
03-24 17:12:29.952: W/dalvikvm(32717): threadid=17: thread exiting with uncaught exception (group=0x415efba8) 
03-24 17:12:33.926: W/jdwp(32717): Debugger is telling the VM to exit with code=1 
+0

로그 고양이주세요! –

+0

메인 스레드에서만 경고 대화 상자를 표시 할 수 있습니다. logcat 여기에 게시 –

+0

로그 고양이를 업데이트했습니다. – Stella

답변

0

합니다 recommened 중대 사용할 수 있지만, 너무 좋지 않다되지 않고, 스레드를 직접 UI 스레드를 업데이트하지 않습니다. UI를 업데이트하고 싶다면

처리기를 사용해야합니다.

Handler mHandler; 

    @Override 
    public void run() 
    { 
     // We got this IP from servlet and stored temporarily, so retrieve it from there. 
     String socketServerIP = ((GlobalStore) RandomIDActivity.this.getApplication()).getSocketIPAddress(); 
     Log.d("socketServerIP", socketServerIP); 

     try { 
      InetAddress serverAddr = InetAddress.getByName(socketServerIP); 
      socket = new Socket(serverAddr, SERVERPORT); 

      pw = new PrintWriter(socket.getOutputStream(), true); 
      EditText randTxtField = (EditText) findViewById(R.id.editText1); 
      pw.println(randTxtField.getText().toString()); 
      //output.write(imgbyte,0,imgbyte.length); 
      pw.flush();    

      // Read randrom ID returned by Socket 
      BufferedReader socketReader; 
      try { 
       socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
       msgStr = socketReader.readLine(); 
       Log.d("msgStr: ", msgStr); 

    //add handler here 
    mHandler.post(new Runnable{ 
public void run(){ 
    if (msgStr.equalsIgnoreCase("SUCCESS")) 
       { 
        socket.close(); 

      // Crashing if I call alert dialog like this. 
        CobrowseAlertDialog("Successfully connected! Click OK to starts screen sharing!", true); 

        //Intent intent = new Intent(context, MainActivity.class); 
        //startActivity(intent); 
       } 
       else 
       { 
        CobrowseAlertDialog("There seems to be problem in connecting..Try connecting it again with proper Random Auth ID!", false); 
       } 
     } 
    }); 





      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
     catch (UnknownHostException e1) { 
      e1.printStackTrace(); 
     } 
     catch (IOException e1) { 
      e1.printStackTrace(); 
     } 

    } 
} 
+0

이와 비슷한 핸들러 코드를 추가 한 후에도 동일한 문제가 발생했습니다. – Stella

+0

안녕하세요, 제대로 작동했습니다! 고맙습니다. "CobrowseAlertDialog"메소드에서 this-> Intent intent = new Intent (context, MainActivity.class)를 사용하여 다음 뷰로 이동하는 코드를 추가 할 때 동일한 플로우에서 한 가지 더 많은 문제가 발생합니다. startActivity (intent); catch되지 않은 예외로 종료하는 스레드로 치명적인 예외를 throw합니다. 그 이유는 무엇일까요? 제발 조언. – Stella

+0

나는 alertbox에서 문맥을 사용하지 말아야한다고 생각한다. 방법은 다음과 같습니다. –

0

배경 스레드가 대화 상자를 팝업 할 수 없다. 할 수있는 일은 대화 상자 모양을 팝업하려면 UI 스레드에서 처리기으로 작업 할 수 있습니다. 다른 하나 개의 대안

또한 안드로이드에서

runOnUiThread(new Runnable(){ 
public void run(){ 
////code for alert dialog 
} 
}); 
0

안드로이드에서 스레드는 UI 스레드를 직접 업데이트하지 않습니다. u는 UR UI를 업데이트 할 경우, u는

클래스 ClientThread를 사용해야하는 것은 {

@Override 
    public void run() 
    { 
     // We got this IP from servlet and stored temporarily, so retrieve it from there. 
     String socketServerIP = ((GlobalStore) RandomIDActivity.this.getApplication()).getSocketIPAddress(); 
     Log.d("socketServerIP", socketServerIP); 

     try { 
      InetAddress serverAddr = InetAddress.getByName(socketServerIP); 
      socket = new Socket(serverAddr, SERVERPORT); 

      pw = new PrintWriter(socket.getOutputStream(), true); 
      EditText randTxtField = (EditText) findViewById(R.id.editText1); 
      pw.println(randTxtField.getText().toString()); 
      //output.write(imgbyte,0,imgbyte.length); 
      pw.flush();    

      // Read randrom ID returned by Socket 
      BufferedReader socketReader; 
      try { 
       socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
       msgStr = socketReader.readLine(); 
       Log.d("msgStr: ", msgStr); 

       if (msgStr.equalsIgnoreCase("SUCCESS")) 
       { 
        socket.close(); 

      // Crashing if I call alert dialog like this. 
        CobrowseAlertDialog("Successfully connected! Click OK to starts screen sharing!", true); 

        //Intent intent = new Intent(context, MainActivity.class); 
        //startActivity(intent); 
       } 
       else 
       { 
        CobrowseAlertDialog("There seems to be problem in connecting..Try connecting it again with proper Random Auth ID!", false); 
       } 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
     catch (UnknownHostException e1) { 
      e1.printStackTrace(); 
     } 
     catch (IOException e1) { 
      e1.printStackTrace(); 
     } 

    } 
} 

처리기 처리기 = 새로운 핸들러()의 Runnable를 구현;

단추 connectBtn = (단추) findViewById (R.id.button2); connectBtn.setOnClickListener (새 View.OnClickListener() {

  @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       handler.post(new Runnable { 

    @Override 
    public void run() 
    { 
     // We got this IP from servlet and stored temporarily, so retrieve it from there. 
     String socketServerIP = ((GlobalStore) RandomIDActivity.this.getApplication()).getSocketIPAddress(); 
     Log.d("socketServerIP", socketServerIP); 

     try { 
      InetAddress serverAddr = InetAddress.getByName(socketServerIP); 
      socket = new Socket(serverAddr, SERVERPORT); 

      pw = new PrintWriter(socket.getOutputStream(), true); 
      EditText randTxtField = (EditText) findViewById(R.id.editText1); 
      pw.println(randTxtField.getText().toString()); 
      //output.write(imgbyte,0,imgbyte.length); 
      pw.flush();    

      // Read randrom ID returned by Socket 
      BufferedReader socketReader; 
      try { 
       socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
       msgStr = socketReader.readLine(); 
       Log.d("msgStr: ", msgStr); 

       if (msgStr.equalsIgnoreCase("SUCCESS")) 
       { 
        socket.close(); 

      // Crashing if I call alert dialog like this. 
        CobrowseAlertDialog("Successfully connected! Click OK to starts screen sharing!", true); 

        //Intent intent = new Intent(context, MainActivity.class); 
        //startActivity(intent); 
       } 
       else 
       { 
        CobrowseAlertDialog("There seems to be problem in connecting..Try connecting it again with proper Random Auth ID!", false); 
       } 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
     catch (UnknownHostException e1) { 
      e1.printStackTrace(); 
     } 
     catch (IOException e1) { 
      e1.printStackTrace(); 
     } 

    } 
} 

); } });

+0

그것의 작동하지 않는다, 예외가있는이 줄 자체에서 실패, socket = new Socket (serverAddr, SERVERPORT); – Stella

+0

핸들러를 사용하면 작동합니다. – Stella

+0

하지만 같은 흐름에서 한 가지 더 많은 문제가 있습니다. "CobrowseAlertDialog"메서드에서 this-> Intent intent = new Intent (context, MainActivity.class)를 사용하여 다음보기로 이동하는 코드를 추가 할 때; startActivity (intent); catch되지 않은 예외로 종료하는 스레드로 치명적인 예외를 throw합니다. 그 이유는 무엇일까요? 제발 조언. – Stella

관련 문제