I’m programming on a Android Game that includes the jDroidlib library. And I want to upload a file that’s written on my sdcard. I downloaded the Apache FTPClient for Java and I found this code to upload it on my server:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("server"));
ftpClient.enterLocalPassiveMode();
ftpClient.login("username", "password");
ftpClient.changeWorkingDirectory("android");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream("storage/sdcard0/Labyrinthal Quest/Scores.txt"));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("Scores.txt", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
catch (Exception e) {
Context context = getApplicationContext();
CharSequence text = "Well, that failed!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
The problem is: if I run this code in one of the jDroidLib-Activities, it works perfectly, but in a normal Android Activity it doesn’t work (shows the Toast “Well, that failed!”).
I also made the permission in the manifest for the app to access the Internet.
I really don’t know what to do. It works in one Activity but not in the other…
Are there any other settings I have to set?
Is there anything I have to set because it only can be executed in a special child thread?
But this code makes a child thread, doesn’t it:
FTPClient ftpClient = new FTPClient();
— UPDATE —
323go said, that I probably got a NetworkOnMainThreadException and that must have been the problem. The network threads have to be childed.
So I just surrounded my code by a new thread and it works now:
new Thread(new Runnable() {
public void run() {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("server"));
ftpClient.enterLocalPassiveMode();
ftpClient.login("username", "password");
ftpClient.changeWorkingDirectory("android");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream("file directory"));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("filename", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
catch (Exception e) {
Context context = getApplicationContext();
CharSequence text = "wurde net hochjeladn!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}).start();
323go said, that I probably got a NetworkOnMainThreadException and that must have been the problem. The network threads have to be childed. So I just surrounded my code by a new thread and it works now: