首页 文章

按钮执行时更新textView? - Android

提问于
浏览
0

我在一个按钮(大过程)中有一个进程 . 我想用diferents值更新TextView . 喜欢:

  • 正在连接......

  • 接收档案......

  • 完成......

等等..

我正在使用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("FAS4-F@S-1-F@S- 1.0.152-F@S-");

            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("PDA1-F@S-"))
           {
                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("FAS4-F@S-1-F@S- 1.0.150-F@S-");


                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("FAS2-F@S-");

                String str2= "";



                clientSocket.setSoTimeout(30000);


                while(true && (!str2.contains("PDA7-F@S-") && !str2.contains("PDAERR1-F@S-")))
                    {
                        s2 = entrada.read(buffer2);  

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

                    }

                clientSocket.setSoTimeout(0);

                String replace1 = str2.replace("PDA7-F@S-", "");
                String replace2 = replace1.replace(" ", "");
                String tamanyArxiu = replace2.replace("-F@S-ZIP","");


                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("PDA3-F@S-") && !str2.contains("PDAERR1-F@S-")))
                    {
                        s2 = entrada.read(buffer2);  

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

                    }

                    clientSocket.setSoTimeout(0);

                    if(str2.contains("PDA3-F@S-"))
                    {
                        sortida.writeBytes("FAS7-F@S-");
                        Thread.sleep(2000);

                        sortida.writeBytes("FAS6-F@S-");
                    }




                    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

    }

}

提前致谢!

大卫 .

3 回答

  • 0

    你正在主线程上执行一个网络操作,点了解这里是Android操作单个主线程所以如果你在服务/活动/内容提供商等上做任何耗时的操作,它将阻止你的主线程,因此所有的东西将看起来他们被阻止/无响应,你会在几秒钟后收到一条ANR消息 .

    总之,请遵循这种方法

    • 将网络扩展代码移动到单独的线程

    • 实现Mesasge处理机制以更新主线程上的UI(Handler / Looper)

    进一步帮助Android为此提供了一个类AsynTask . 您可以在doInBackground()中执行操作,条件是您可以通过onProcessUpdate()更新UI

    希望这可以帮助 .

  • 0

    Internet连接是阻止操作,即它阻止UI直到操作完成(这就是为什么只能看到最后一次更新) . 您必须将其移动到线程(甚至更好地移动到AsyncTask) . 但是你得到另一个问题,你无法从主线程外部更新UI . 因此,您必须使用Handler来更新UI .

  • 0

    如果您在UI线程上运行此过程,可能会导致提示“Applicaiton”对话框
    没有回应“ . 所以我建议这个任务必须在AsyncTask或服务中完成

    您可以更新文本视图

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

    例如,下载文件

    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");
         }
     }
    

相关问题