2012-09-24 83 views
0

我在一個按鈕(大進程)中有一個進程。我想用不同的值更新TextView。像:按鈕執行時更新textView? - Android

  • 連接...
  • 接收文件...
  • 完整...

等。

我使用的setText(); void,但我只能得到setText();的最後一個值,在這種情況下:

estatEdit.setText(「Tareas completadas!」);

這裏是我的代碼...

public class sincroGeneral extends Activity implements OnClickListener { 
    private static final String CATEGORIA = "libro"; 
    private static final String HOST = "192.168.1.165"; 
    private static final int PORT = 9889; 
    private static final int PORTDATOS = 9888; 

    int filesize=6022386; 
    int bytesRead; 
    int current = 0; 

    byte [] mybytearray = new byte [filesize]; 

    byte buffer[] = new byte[1024]; 
    byte buffer2[] = new byte[1024]; 
    byte bufferArxiu[] = new byte[2048]; 
    int s; 
    int s2; 
    String Benvinguda; 
    String compra; 
    EditText estatEdit; 
    EditText editInflated; 

    File myfile; 

    SQLiteDatabase baseDatos; 
    LinearLayout mainLayout; 
    View view2; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle bundle) { 
     super.onCreate(bundle); 
     setContentView(R.layout.sincrolayout); 



     Button b = (Button) findViewById(R.id.BotoEnviarSincro); 
     b.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 

       Button b = (Button) findViewById(R.id.BotoEnviarSincro); 
       estatEdit = (EditText) findViewById(R.id.editSincro); 

       estatEdit.setText("Enviando petición..."); 



       b.setClickable(false); 
       b.setFocusable(false); 
       b.setEnabled(false); 


       ProcesRebre(); 

       b.setClickable(true); 
       b.setFocusable(true); 
       b.setEnabled(true); 
      } 
      }); 
    } 




    private void mostrarMensaje(String mensaje) 
    { 
     Toast.makeText(this, mensaje, 500).show(); 
    } 


    private void ProcesRebre() 
    { 
     Socket sockDatos = null; 
     Socket clientSocket = null; 



     DataOutputStream sortida; 
     DataInputStream entrada; 
     BufferedReader inFromServer; 


     DataOutputStream sortidaDatos; 
     DataInputStream entradaDatos; 
     BufferedReader inFromServerDatos; 






     try { 
      estatEdit.setText("Conectando..."); 

      clientSocket = new Socket(HOST, PORT); 




      sortida = new DataOutputStream(clientSocket.getOutputStream()); 
      entrada = new DataInputStream(clientSocket.getInputStream()); 
      inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 




      sortida.writeBytes("[email protected]@S- [email protected]"); 

      Log.i("Enviat","OK"); 

      clientSocket.setSoTimeout(30000); 

      s = entrada.read(buffer); 
      String str = new String(buffer, "UTF8"); 


      clientSocket.setSoTimeout(0); 


      Log.i("Rebut","OK"); 

      if(str.contains("[email protected]")) 
      { 
       sockDatos = new Socket(HOST, PORTDATOS); 

       estatEdit.setText("Esperando archivo...."); 
       sortidaDatos = new DataOutputStream(sockDatos.getOutputStream()); 
       entradaDatos = new DataInputStream(sockDatos.getInputStream()); 
       inFromServerDatos = new BufferedReader(new InputStreamReader(sockDatos.getInputStream())); 



       sortidaDatos.writeBytes("[email protected]@S- [email protected]"); 


       if(sockDatos.isConnected()) 
       { 
        System.out.println("Conectat amb port 9888"); 
       } 

       File carpetaSincro = new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/"); 
       carpetaSincro.mkdirs(); 

       File ArxiuSincro = new File (Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip"); 

       if(ArxiuSincro.exists()) 
       { 
        ArxiuSincro.delete(); 
       } 

       File ArxiuSincro2 = new File (Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip"); 
       ArxiuSincro2.createNewFile(); 


       sortida.writeBytes("[email protected]"); 

       String str2= ""; 



       clientSocket.setSoTimeout(30000); 


       while(true && (!str2.contains("[email protected]") && !str2.contains("[email protected]"))) 
        { 
         s2 = entrada.read(buffer2); 

         str2 = new String(buffer2, "UTF8"); 

        } 

       clientSocket.setSoTimeout(0); 

       String replace1 = str2.replace("[email protected]", ""); 
       String replace2 = replace1.replace(" ", ""); 
       String tamanyArxiu = replace2.replace("[email protected]",""); 


       int bufferZip = Integer.parseInt(tamanyArxiu); 

       boolean in; 
       s2 = 0; 
       sockDatos.setSoTimeout(30000); 
       RandomAccessFile archivo = new RandomAccessFile(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip", "rw"); 
       long tamArxActual = 0; 

        while(bufferZip>=tamArxActual) 
        { 
         sockDatos.setSoTimeout(10000); 
         s2 = entradaDatos.read(bufferArxiu); 
         estatEdit.setText("Recibiendo archivo...."); 
         archivo.write(bufferArxiu); 

         tamArxActual = archivo.length(); 

         Thread.sleep(2); 
        } 

        sockDatos.setSoTimeout(0); 

        estatEdit.setText("Archivo recibido"); 

        str2 = ""; 

        clientSocket.setSoTimeout(30000); 

        while(true && (!str2.contains("[email protected]") && !str2.contains("[email protected]"))) 
        { 
         s2 = entrada.read(buffer2); 

         str2 = new String(buffer2, "UTF8"); 

        } 

        clientSocket.setSoTimeout(0); 

        if(str2.contains("[email protected]")) 
        { 
         sortida.writeBytes("[email protected]"); 
         Thread.sleep(2000); 

         sortida.writeBytes("[email protected]"); 
        } 




        sockDatos.close(); 
        clientSocket.close(); 


        String pathZip = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip"; 
        String directoriExtraccio = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/"; 
        String pathTxt = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"; 
        UnzipUtility unzipper = new UnzipUtility(); 

        try { 
         unzipper.unzip(pathZip, directoriExtraccio); 
        } catch (Exception ex) { 
         System.out.print("No s'ha pogut descomprimir l'arxiu"); 
         ex.printStackTrace(); 
        } 

        File f = new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.dll"); 
        f.renameTo(new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt")); 


        importarSincro(); 





      } 


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




    private void importarSincro() throws SQLException, IOException 
    { 

     int contador = 0; 
     String LiniaSQL; 


     FileInputStream fstream = new FileInputStream(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"); 
     DataInputStream DataInFile = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(
       new InputStreamReader(new FileInputStream(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"), "Latin-1")); 

     String FinalSQL = ""; 

     baseDatos = openOrCreateDatabase("BBDD", MODE_WORLD_WRITEABLE, null); 

     baseDatos.execSQL("BEGIN"); 
     while ((LiniaSQL = br.readLine()) != null) { 



      if(contador > 0) 
      { 
       FinalSQL = LiniaSQL.replace("***** ", ""); 
       if(FinalSQL.contains("DELETE") && !FinalSQL.contains("DELETE FROM")) 
       { 
        FinalSQL = FinalSQL.replace("DELETE", "DELETE FROM"); 

        try{ 
         baseDatos.execSQL(FinalSQL); 
        }catch(SQLiteException e){ 


        } 
       } 
       else 
       { 
        try{ 
         baseDatos.execSQL(FinalSQL); 
        }catch(SQLiteException e){ 


        } 
       } 






       LiniaSQL = ""; 
      } 

      contador++; 

     } 
     baseDatos.execSQL("COMMIT"); 
     estatEdit.setText("Tareas completadas!"); 
     baseDatos.close(); 



    } 


    ///////////////////////////////////////// 


    public static String deserializeString(File file) 
       throws IOException { 
        int len; 
        char[] chr = new char[4096]; 
        final StringBuffer buffer = new StringBuffer(); 
        final FileReader reader = new FileReader(file); 
        try { 
         while ((len = reader.read(chr)) > 0) { 
          buffer.append(chr, 0, len); 
         } 
        } finally { 
         reader.close(); 
        } 
        return buffer.toString(); 
       } 




    public void onClick(View arg0) { 
     // TODO Auto-generated method stub 

    } 

} 

提前感謝!

David。

回答

0

互聯網連接是一種阻止操作,即它阻止用戶界面,直到操作完成(這就是爲什麼只有最後一次更新被看到)。你必須將它移動到一個線程(或者更好的是一個AsyncTask)。但是接下來你會遇到另一個問題,你不能從主線程外部更新UI。所以,你必須使用Handler來更新UI。

+0

你能給我一個小例子? – Ezrou

+0

檢查此(http://developer.android.com/guide/components/processes-and-threads.html#Threads)和此http://developer.android.com/reference/android/os/AsyncTask.html –

+0

謝謝!成功了! :) – Ezrou

0

你正在主線程上執行一個網絡操作,這裏要指出的是Android是在一個主線程上運行的,所以如果你對服務/活動/內容提供者等進行任何耗時的操作,它會阻塞你的主線程,因此所有的東西都會看起來像是被阻止/不響應,事實上你會在幾秒鐘後收到一條ANR消息。

得出結論,按照這個方法

  1. 移動網絡廣泛的代碼到一個單獨的線程
  2. 實現一個Mesasge處理機制來更新您的主線程UI(處理器/尺蠖)

進一步提供幫助Android爲此提供了一個類AsynTask。您可以在doInBackground()中執行操作,並且可以通過onProcessUpdate()更新您的UI,但希望這有助於您更好地使用UI。

0

如果您運行UI線程此過程中,可能會導致提示一個對話框,說:「應用程序了
沒有響應」。所以我建議這個任務必須做到無論在AsyncTask或服務

U可以更新您的文本鑑於

onPreExecute() 
onProgressUpdate() 
onPostExecute() functions in AsyncTask. 

Eg.for下載文件

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
    protected Long doInBackground(URL... urls) { 
     int count = urls.length; 
     long totalSize = 0; 
     for (int i = 0; i < count; i++) { 
      totalSize += Downloader.downloadFile(urls[i]); 
      publishProgress((int) ((i/(float) count) * 100)); 
      // Escape early if cancel() is called 
      if (isCancelled()) break; 
     } 
     return totalSize; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     setProgressPercent(progress[0]); 
    } 

    protected void onPostExecute(Long result) { 
     showDialog("Downloaded " + result + " bytes"); 
    } 
}