1

Hey I am trying to upload an image to my ftp server but from some reason the connection isn't working and I can figure out why..

here is the connection code:

 public  void uploadingFilestoFtp() throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;
    boolean result;


    try {
        ftpclient.connect(host);

        result = ftpclient.login(username, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/");

        File file = new File(imagePath);
        fis = new FileInputStream(file);

        // Upload file to the ftp serverresult = ftpclient.storeFile(testName, fis);

        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

I am using exactly the details of the ftp server but it doesn't seems to work

How can I get this mehod to work?

user7415791
  • 449
  • 1
  • 7
  • 11

1 Answers1

0
android.os.NetworkOnMainThreadException

You are trying to make a network request from the UI thread. Android doesn't allow any network request from main(UI) thread. You need to create a class extending AsyncTask.

public class UploadFileTask extends AsyncTask <Void, Void, Void > {

    public void onPreExecute() {

    }

    public void doInBackground(Void...unused) {
        uploadingFilestoFtp(); //Call your method here. Put necessary try-catch block.
    }

    public void onPostExecute(Void unused) {
        // do something when upload is done.
    }
}

Note that this onPreExecute() and onPostExecute() run on the UI thread. So you can do any stuff before or after the network call. Make the network call in doInBackground() method.

Check this answer How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
Abhishek Jain
  • 3,562
  • 2
  • 26
  • 44