3

I am new to android and java programing. I write following code to connect to ftp server

public class NewMainActivity extends Activity {
TextView Display;
//declare a public FTP client object.
public FTPClient mFTPClient = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_main);
    final TextView Display = (TextView) findViewById(R.id.tvResults);

    try {
         mFTPClient = new FTPClient();

          // connecting to the host
         mFTPClient.connect("www.filegenie.com",21); 

          // now check the reply code, if positive mean connection success
          if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
              // login using username & password
              boolean status = mFTPClient.login("user", "MyPassword");

              // Set File Transfer Mode

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

              Display.setText("Correct"+ String.valueOf(status)); //return status;
          }

        }catch(Exception e) {
             Display.setText(" Exception message is = "+e.getMessage()+" Reply code = "+mFTPClient.getReplyCode());

        }

}

When I run this code I get no specific error but the program didn't execute mFTPClient.connect method and jumps to the 'Exception' part and I get "null" as exception getMessage and "0" as ReplyCode. I have import all the required files such as

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

I am using eclipse and ADT Build v22.0.1-685705. I have also included commons-net-3.3, commons-net-3.3-sources and commons-net-examples-3.3 files in the android project's lib, and also included the java files and folders from commons-net-3.3-src | src | main | java | org | apache | commons | net folder to the Android project's src folder by creating the folders org | apache | commons | net. I could not figured out what is the problem. Can any one help me in this regard.

The same server can be accessed with a comercial ftp client.

Thanks in advance.

1 Answers1

4

I've tried your code and it works ok. Based on the response code you're getting I assume the connection to the server has not been even established. Make sure you have granted your app with INTERNET permission in the manifest file:

<uses-permission android:name="android.permission.INTERNET" /> 

EDIT: From the exception stack trace it's clear, that you're trying to execute this code from a main thread. In Android 3.0 (Honeycomb) or later you're not permitted to execute any network call in UI thread by default. The reason is simple: network call may block for an indefinite amount of time, effectively freezing application UI. You have two options how to fix it:

Lazy way - Disable therad check for network calls:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                                     .permitAll()
                                     .build();   
StrictMode.setThreadPolicy(policy);

You can always enable thread checks again using

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                                     .detectAll()
                                     .penaltyLog()
                                     .penaltyDeath()
                                     .build();
StrictMode.setThreadPolicy(policy);

Proper way - execute FTP calls from a background worker thread using AsyncTask. Take a look here for examples and comprehensive explanation about AsyncTasks.

Jk1
  • 11,233
  • 9
  • 54
  • 64
  • Dear, thanks for the reply, I have already tried the INTERNET permission but it still not working. Do you need to apply any other special setting for the code? – Mudasser Naseer Sep 03 '13 at 17:45
  • @MudasserNaseer, is it possible to get type of exception and a stack trace? – Jk1 Sep 03 '13 at 18:42
  • I got the following stack trace, I don't know how to ge type of exception. Part-I: android.os.NetworkOnMainThreadException\n\tat android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)\n\tat java.net.InetAddress.lookupHostByName(InetAddress.java:385)\n\tat java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)\n\tat java.net.InetAddress.getByName(InetAddress.java:289)\n\tat org.apache.commons.net.SocketClient.connect(SocketClient.java:203)\n\tat com.example.new_1.NewMainActivity.onCreate(NewMainActivity.java:27)\n\tat – Mudasser Naseer Sep 03 '13 at 19:24
  • Part-2 android.app.Activity.performCreate(Activity.java:5104)\n\tat android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)\n\tat android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)\n\tat android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)\n\tat android.app.ActivityThread.access$600(ActivityThread.java:141)\n\tat android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)\n\tat android.os.Handler.dispatchMessage(Handler.java:99)\n\tat android.os.Looper.loop(Looper.java:137)\n\tat – Mudasser Naseer Sep 03 '13 at 19:26
  • Part-3 android.app.ActivityThread.main(ActivityThread.java:5041)\n\tat java.lang.reflect.Method.invokeNative(Native Method)\n\tat java.lang.reflect.Method.invoke(Method.java:511)\n\tat com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)\n\tat com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)\n\tat dalvik.system.NativeStart.main(Native Method)\n – Mudasser Naseer Sep 03 '13 at 19:26
  • Thanks, it's quite clear now. Please refer to the edited answer. – Jk1 Sep 03 '13 at 20:11
  • Dear JK1 thanks for the reply, the problem is solved. I used the Lazy way. I don't know how to use AsyncTasks but I will go through it and try to use it. Can you send me the syntax to enable again the thread check for network calls after completing a specific task. Thanks again for the help. – Mudasser Naseer Sep 04 '13 at 19:30
  • See updated answer. I strongly recommend, however, using AsyncTasks. They are highly useful tool for Android developer. – Jk1 Sep 04 '13 at 19:56