Sending a CSV file to an ftp server

Asked

Viewed 250 times

0

My application makes an order registration, already creating a file CSV and throwing that file into FTP, the registered application creates the CSV, but when to upload to ftp error(I think), follows the code:

Class makes request:

Confirmar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String atString = atendente.getText().toString();
                String mesaString = meCodigo;
                String resultadoPe;
                String resultadoPp = null;

                resultadoPe = crud.inserePedido(data, hora, atString, mesaString);
                Toast.makeText(getApplicationContext(), resultadoPe, Toast.LENGTH_LONG).show();

                Cursor cursor = crud.pegaIdPedido();
                pedItem = cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.getPedCodigo()));
                String all = edtTotal.getText().toString();
                final ArrayList<Produtos> produtos = produtosAdapter.getProdutos();
                int linhas = produtos.size();

                for (int i = 0; i < linhas; i++) {
                    Produtos linha = produtos.get(i);
                    String id = linha.getId();
                    String unitario = linha.getUnidade();
                    String quantidade = linha.getQtd();

                    resultadoPp = crud.insereProduto(id, pedItem, unitario, all, quantidade);
                }

                Toast.makeText(getApplicationContext(), resultadoPp, Toast.LENGTH_SHORT).show();

                int linhasPe = crud.carregaPedido(Integer.parseInt(pedItem));
                int linhasPp = crud.carregaProdutos(Integer.parseInt(pedItem));

                crud.escrever(linhasPe, linhasPp, Integer.parseInt(pedItem));

                dialog = ProgressDialog.show(RealizarPedidoActivity.this,"Aguarde...", "Sincronizando dados...",
                        false, true);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        efetuarUpload();
                        dialog.dismiss();
                    }
                }).start();



               AlertDialog.Builder builder = new AlertDialog.Builder(RealizarPedidoActivity.this);
                builder.setTitle("Atenção");
                builder.setMessage("Desaja realizar um pedido para outra mesa?");
                builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(RealizarPedidoActivity.this, ListarMesaActivity.class);
                        startActivity(i);
                        finish();
                    }
                });

                builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(RealizarPedidoActivity.this, MainActivity.class);
                        startActivity(i);
                        finish();
                    }
                });

                alerta = builder.create();
                alerta.show();
            }
        });
}

public void efetuarUpload(){
        try{
            FTPController ftp = new FTPController();
            ftp.conectar("192.168.2.5", "vitor", "248693751qQ", 21);
            ftp.upload("export.csv", "/export/export.csv");
        }catch (Exception e){
            e.getStackTrace();
        }
    }

Class Ftpcontroller:

package realsysten.com.br.sigarestaurante;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import android.os.Environment;
import android.util.Log;

/**
 * Created by Vitor on 14/06/2016.
 */
public class FTPController{

    FTPClient mFTP;
    private String TAG = "classeFTP";

    public FTPFile[] dir(String diretorio) {
        try {
            FTPFile[] ftpFiles = mFTP.listFiles(diretorio);
            return ftpFiles;
        } catch (Exception e) {
            Log.e(TAG, "Erro: não foi possivel listar os arquivos e pastas do diretorio " +
                    diretorio + " . " + e.getMessage());
        }
        return null;
    }

    public boolean mudarDiretorio(String diretorio) {
        try {
            mFTP.changeWorkingDirectory(diretorio);
        } catch (Exception e) {
            Log.e(TAG, "Erro: não foi possivel mudar o diretorio para " + diretorio);
        }

        return false;
    }

    public boolean desconecta() {
        try {
            mFTP.disconnect();
            mFTP = null;
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Erro: ao desconectar. " + e.getMessage());
        }
        return false;
    }

    public boolean conectar(String host, String usuario, String senha, int porta){
        try {
            mFTP = new FTPClient();
            mFTP.connect(host, porta);
            if (FTPReply.isPositiveCompletion(mFTP.getReplyCode())) {
                boolean status = mFTP.login(usuario, senha);

                mFTP.setFileType(FTP.BINARY_FILE_TYPE);
                mFTP.enterLocalPassiveMode();

                return status;
            }
        } catch (Exception e) {
            Log.e(TAG, "ERRO: não foi possivel conectar " + host);
        }
        return false;
    }

    public boolean download(String diretorioOrigem, String arqOrigem, String arqDestino) {
        boolean status = false;

        try {
            mudarDiretorio(diretorioOrigem);
            FileOutputStream desFileStream = new FileOutputStream(arqDestino);
            mFTP.setFileType(FTP.BINARY_FILE_TYPE);
            mFTP.enterLocalActiveMode();

            status = mFTP.retrieveFile(arqOrigem, desFileStream);
            desFileStream.close();
            desconecta();
            return status;
        } catch (Exception e) {
            Log.e(TAG, "Erro: Falha ao efetuar download. " + e.getMessage());
        }
        return status;
    }

    public boolean upload(String diretorio, String nomeArquivo) {
        boolean status = false;
        try {
            FileInputStream arqEnviar = new FileInputStream(Environment.getExternalStorageDirectory() + diretorio);
            mFTP.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
            mFTP.setFileType(FTPClient.STREAM_TRANSFER_MODE);
            mFTP.storeFile(nomeArquivo, arqEnviar);
            desconecta();
            return status;
        } catch (Exception e) {
            Log.e(TAG, "Erro: falha ao efetuar upload. " + e.getMessage());
        }
        return status;
    }
}

debugging the aplciativo, arriving at these lines:

    new Thread(new Runnable() {
            @Override
            public void run() {
                efetuarUpload();
                dialog.dismiss();
            }
        }).start();

Nothing happens at all, just arrives at new Thread(new Runnable() { ,

and jumps right to:

AlertDialog.Builder builder = new AlertDialog.Builder(RealizarPedidoActivity.this);
                builder.setTitle("Atenção");
                builder.setMessage("Desaja realizar um pedido para outra mesa?");
                builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {

it’s not enough to even enter the thread

Does anyone know why?

NOTE: No error in the Log.

  • 1

    When debugging you will need to put a breakpoint inside run() to see how the method is executing and gets to execute. This behavior that you say ("happens absolutely nothing, jumps straight to") is what should happen, because it is the definition of an anonymous class. Put the bug here to see what’s going on.

  • 1

    And another, for those who put a negative in the question, I think it’s easier to help the colleague here than to judge him without adding anything?

  • the only thing I found in my log that seems to be a mistake is: Skipped 31 frames! The application may be doing too much work on its main thread.

  • or this: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa213f540, error=EGL_SUCCESS

  • 1

    Behold can help. I’m not very close to android.

  • It did help, it did give some problems in the InputStream, but it was written wrong directory, however, it runs but saves nothing on FTP

  • AE managed to make it work and export into FTP, thank you @Gustavocinque, a question you know how to export inside a folder in FTP? it is exporting on FTP root

  • 1

    If you use the FTPController#mudarDiretorio(String)before the update would not work? I never used ftp but I can try to find an answer.

  • tried to use changeDirectory did not work

  • 1

    @Gustavocinque let what, I who was passing the wrong value to the changeDirectory, now got, thanks for your attention ^^

  • Well, if everything worked out in the end, try to create an answer to your question, post it, and then put it as the accepted answer. As you derived your own answer, there might be someone with the same problem, and end up here.

Show 6 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.