2012-06-22 3 views
-1

작성하기 전에 다른 게시물을 보았지만 해결책을 찾지 못했습니다. 도움을 주시면 감사하겠습니다.업데이트 UI Android

응용 프로그램 시작 프로그램 클래스의 onCreate 메서드에서 스레드 TCPServer를 만들고 정보가있는 테이블을 표시합니다. 문제는이 정보가 다양하므로 스레드가 TCPServer가 새 메시지 컨트롤을 보냈을 때이를 업데이트해야한다는 것입니다.

그럼 자신을 잘 표현하면 코드를 보여줍니다.

//launcher class 
public class profesor extends Activity implements OnClickListener { 

    static TableLayout alumnsTable; 

    @Override 
    public void onCreate(Bundle savedInstanceState) {    
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     . 
     . 
     . 

     Thread serverThread = new Thread(null, new TCPServer(), "BackgroundService"); 
     serverThread.start(); 
     . 
     . 
     .  

     //information is added to the table   
     alumnsTable = (TableLayout)findViewById(R.id.alumnsTable); 
     List<Alumnos> listaAlumnos = Alumnos.ReadList(); 
     for(Alumnos al:listaAlumnos){ 
      alumnsTable.addView(filaAlumno(al)); 
     } 
    } 

    //Eliminates the above information and reloads the table with the new information 
    public void actualiza(){ 
     alumnsTable.removeAllViews(); 
     setContentView(R.layout.main); 
     alumnsTable = (TableLayout)findViewById(R.id.alumnsTable);       
     List<Alumnos> listaAlumnos = Alumnos.ReadList();                         
     for(Alumnos al:listaAlumnos){ 
      alumnsTable.addView(filaAlumno(al)); 
     } 
    } 
} 


//TCPServer class 
public class TCPServer implements Runnable { 
    private static Handler handler = new Handler(); 


    public void run() { 

    ServerSocket serverSocket; 

    String file; 
    int filesizeMb = 4; 
    int filesize = filesizeMb * (1024 * 1024); // filesize temporary hardcoded 


    int bytesRead; 
    int current = 0; 
    try { 
     serverSocket = new ServerSocket(profesor.COMUNICATION_PORT); 
     Log.d(profesor.LOG_TAG,"S: Servidor Iniciado."); 

     while (true) { 
      final Socket sock = serverSocket.accept(); 
      String ClientAddr=sock.getInetAddress().toString(); 
      ClientAddr = ClientAddr.substring(ClientAddr.indexOf('/') + 1, ClientAddr.length()); 
      final String contacto=DeviceList.getDeviceName(ClientAddr); 
      Log.d(profesor.LOG_TAG,"S: Conectado con: " + ClientAddr); 

      // Conection type 
      DataInputStream dis = new DataInputStream(sock.getInputStream()); 
      final String connectionType =dis.readUTF(); 
      Log.d(profesor.LOG_TAG,"S: Tipo de Conexion " + connectionType); 

      . 
      . 
      . 
      . 

      // RECEIVING CONTROL MESSAGE 
      if (connectionType.contains("CONTROL")) { 
       String ControlText =dis.readUTF(); 
       String[] Control = ControlText.split(":"); 
       Log.d(profesor.LOG_TAG,"S: Recibido nuevo progreso de prueba. IP: "+Alumnos.getIdAlumno(ClientAddr)+"->"+Integer.parseInt(Control[0])+" ->"+Integer.parseInt(Control[1])); 

       Alumnos.setProgress(Alumnos.getIdAlumno(ClientAddr), Integer.parseInt(Control[0]), Integer.parseInt(Control[1])); 


       /****************************************************/ 
       //Here is where I need to call the update method of the 
       //class teacher to delete the old data and fill the table 
       //again. 
       /****************************************************/ 
      } 
      dis.close(); 
      sock.close(); 
     } 

     } catch (IOException e) { 
      Log.d(profesor.LOG_TAG, "IOException"+e); 
      e.printStackTrace(); 
     } 
    } 
} 

누구나 내게 어떤 아이디어를 줄 수 있습니까?, 예제 핸들러를 보았지만 클래스 선언 및 다른 호출에서는 볼 수 없었습니다.

나는 당신이 내 뜻을 이해하기를 바랍니다, 제 영어는별로 좋지 않습니다. 도움을

감사

+0

stackoverflow에 오신 것을 환영합니다. 이것은 여러 가지 사건에 대해 논의되었습니다. http://stackoverflow.com/questions/4369537/update-ui-from-thread – Orlymee

답변

1

당신은 UI 업데이트 할 때 당신은 핸들러 또는 활동 참조로 tcpserver는을 만든 다음 그것을 사용하려고 할 수 있습니다에서 UI를 업데이트하는

refHandler.post(new Runnable(){ 
    public void run() { 
     //Update 
    } 
}); 

refActivity.runOnUiThread(new Runnable() { 
    public void run() { 
     //Update 
    } 
}); 
+0

빠른 응답을 주셔서 감사합니다. 그러나이 두 가지 형식을 시도했지만 작동하지 않습니다. 이클립스는 내 경우 전문가의 refActivity를 인식하지 못합니다. 정적 메소드에서 Eclipse가 업데이트되면 클래스 프로파일 러의 업데이트 된 메소드에서 "setContentView (R.layout.main)"오류가 발생합니다. 나 do not는 알고있다 – user1177917

+0

내가 보았던 것에서, 문제는 내가 Thread TCP에있을 때 컨텍스트가 손실된다라는 것이다. 컨텍스트를 보호하기 위해 클래스 교실에 쓰레드가 전달되는 과정에서 어떻게 잃을 수 있습니까? 감사합니다. – user1177917

0

사용 runOnUiThread을 글타래 (쓰레드) :

// RECEIVING CONTROL MESSAGE 
      if (connectionType.contains("CONTROL")) { 
       String ControlText =dis.readUTF(); 
       String[] Control = ControlText.split(":"); 
       Log.d(profesor.LOG_TAG,"S: Recibido nuevo progreso de prueba. IP: "+Alumnos.getIdAlumno(ClientAddr)+"->"+Integer.parseInt(Control[0])+" ->"+Integer.parseInt(Control[1])); 

       Alumnos.setProgress(Alumnos.getIdAlumno(ClientAddr), Integer.parseInt(Control[0]), Integer.parseInt(Control[1])); 


       /****************************************************/ 
       //Here is where I need to call the update method of the 
       //class teacher to delete the old data and fill the table 
       //again. 
       /****************************************************/ 
    profesor.this.runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      // refresh ui here 
     } 
    }); 
     } 
+0

이렇게하려면 profesor.this에서 오류 (범위에서 접근 할 수있는 유형의 profesor 인스턴스를 포함 할 수 없음)가 있습니다. profesor.actualiza() public void을 호출 할 때 다음 오류가 발생합니다 (profesor 유형의 정적이 아닌 메서드 actualizarPantalla()에 대한 정적 참조를 만들 수 없음). 정적 메서드 메서드 업데이트로 프레임이 있으면 클래스 profesor의 setContentView (R.layout.main) 업데이트 메서드에서 동일한 오류가 발생합니다. 나는 미쳐 갈거야 – user1177917

+1

내가 본 바로는 문제는 스레드 TCP에있을 때 컨텍스트가 손실된다는 것입니다. 컨텍스트를 보호하기 위해 클래스 교실에 쓰레드가 전달되는 과정에서 어떻게 잃을 수 있습니까? 감사합니다. – user1177917