How to check if my App is downloading a file from FTP - android

I am trying to download a file from FTP via my app. But neither of my toasts show. How can I check if I am connected and if the file is downloaded?
Code:
package no.kraftpriser.oversikt;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.SocketException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
public class KraftpriserActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FTPClient ftp;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
int duration2 = Toast.LENGTH_LONG;
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
try {
int reply;
String server = "62.97.235.213";
int port = 21;
ftp.connect(server, port);
ftp.login("anonymous","nobody");
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory("/Fastpris");
InputStream inStream = ftp.retrieveFileStream("2011.txt");
CharSequence tilkoblet = "Connected!";
Toast toastTilkoblet = Toast.makeText(context, tilkoblet, duration2);
toastTilkoblet.show();
reply = ftp.getReplyCode();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
if (ftp.isConnected()) {
try {
ftp.disconnect();
}
catch (IOException f) {
//Do nothing
}
}
CharSequence ikkeTikoblet = "Kunne ikke koble til server";
Toast toastIkkeTilkoblet = Toast.makeText(context, ikkeTikoblet, duration);
toastIkkeTilkoblet.show();
e.printStackTrace();
}
}
}

Your "connected" toast wouldn't show until your transfer is complete since getFileAsStream will block until the transfer is completed. Additionally, you're just loading the file into an InputStream in the code above... you still need to write that input stream to a file if you want to persist it to your SD card or internal storage.
To be able to see the progress of the download, you'd need to do the actual download in a background thread (use AsyncTask). You can then post status updates back to the UI thread via the onProgressUpdate method.
Depending on the FTP client you're using, you can also probably check the return value from the connect and/or login method to see if each of those operations was successful.

Related

Android Socket Client through IOException

package com.example.tristan.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
private Socket client;
int serverPort = 8888;
String serverIP = "192.168.1.6";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fctClient();
}
public void fctClient() {
try {
Toast toast = Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT);
InetAddress addr = InetAddress.getByName(serverIP);
SocketAddress socketAddress = new InetSocketAddress(addr,serverPort);
//SocketAddress socketAddress = new InetSocketAddress(serverIP, serverPort);
client = new Socket();
toast.show();
client.connect(socketAddress);
toast.show();
toast.show();`enter code here`
client.close();
} catch (UnknownHostException e) {
Toast toast = Toast.makeText(getApplicationContext(), "KO1", Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(getApplicationContext(), "KO2", Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
}
}
Hello,
I am trying to connect a client on Android on a Python server using a socket. The Python server is working well but the Android code fails to connect the server passing through a IOException.
Is anyone able to tell me my mistake? The code fails on line "client.connect(socketAddress);". This let me think that the wrong command is used to generate socketAddress.
I found the following link which met the same problem but his solution doesn't work for me.
(Java/Android) Client-side Socket throwing IOException
Thanking you in advance,
TL
You have a NetworkOnMainThreadExeption clearly visible in the logcat. All internet code should be executed in a thread or AsyncTask.
If you modify your code then remove all Toasts as they cannot be called in a thread or the doInBackground of an AsyncTask.

my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?

i am new by android.I have started work with a simple chat app. I wrote a short code by UDP socket one for client and one for server.Now i have some issues at connectivity android real device which client app installed on it , and emulator device which server app run on it.
Client app is a simple code which must set IP for connection to emulator and also has a EditText for sending a message.(I at this point set 10.0.2.2 or 10.0.2.15. But my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?)
Server app has only a textView for getting and showing recived message.
here is Client code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClienttextchatActivity extends Activity
{
private String udpMsg=null;
Handler hand=new Handler();
EditText edtSetIp=null , edtText=null;
Button btnSetIp=null , btnSend=null;
static String ip=null;
static final String LOG_TAG = "UdpStream";
static final int PORT = 8888;
static final int BUF_SIZE=4096;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtText=(EditText)findViewById(R.id.edtText);
edtSetIp=(EditText)findViewById(R.id.edtSetIp);
btnSetIp=(Button)findViewById(R.id.btnSetIp);
btnSend=(Button)findViewById(R.id.btnSend);
btnSetIp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ip=edtSetIp.getText().toString();
}
});
btnSend.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread mythread=new Thread(new th1() );
mythread.start();
}
});
}
//#############################################
public class th1 implements Runnable
{
public void run()
{
udpMsg =edtText.getText().toString();
Log.d(LOG_TAG,udpMsg);
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName(ip);
Log.d(LOG_TAG,"address server address created.");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, PORT);
ds.send(dp);
Log.d(LOG_TAG,"packet send.");
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
}//end run
}//end class th
}
Make sure emulator is started, then in ADB shell, type this command, it will show ip address of emulator.
adb shell
ifconfig etho

UDP on Android emulator

I'm trying to establish a simple UDP connection between a client program running on an android emulator and a server, on two different systems. The server side is fine, but the client side keeps crashing. Is it a problem with the emulator? Should i redirect the port to make it work?
CLIENT SIDE (on android emulator):
package com.example.clientrecv;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
public String text;
public int serverport=1234;
public byte[] message=new byte[1000];
public Button b;
public DatagramPacket p;
public DatagramSocket s;
public Toast t;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.button1);
try {
p = new DatagramPacket(message,message.length);
s = new DatagramSocket(serverport);
try {
s.receive(p);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text= new String(message,0,p.getLength());
Log.d("hello","the message:"+text);
s.close();
// TODO Auto-generated method stub
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showmsg()
{
t=Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
t.show();
}
}
SERVER SIDE: (on pc)
import java.io.*;
import java.net.*;
class serversend
{
public static void main(String args[]) throws Exception
{
String strmsg="Server says hello";
int serverport=1234;
int len=strmsg.length();
System.out.println("starting");
byte[] message=strmsg.getBytes();
try{
InetAddress local=InetAddress.getByName("localhost");
DatagramSocket s=new DatagramSocket();
DatagramPacket p=new DatagramPacket(message,len,local,serverport);
System.out.println("Running");
s.send(p);
System.out.println("Sent");
}catch(Exception e)
{
System.out.println("caught");
}
}
}
There are many example available that can help you to communicate between server and client using UDP
to communicate between these two should add the client port on server side
InetAddress local = InetAddress.getByName("192.168.1.102");
here are the Following Link For Client Server Communication Using UDP
LINK UDP1
Link UDP2
Android after 3.0 version doesn't allow you to implement networking operations within the main UI Thread. You must define a new Thread for that... Here is how you can do it:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//here you Set up you parameters and launch the thread (e.g):
this.newThread = new Thread(new mThread());
this.newThread.start();
/* Next you define your newThread's run method in wich all networking
operations must take place*/
class mThread implements Runnable {
public void run() {
// Do all networking tasks you need
}
}

Accessing Text File from FTP Server, Android Development

I am trying to access files on an FTP server in Android.
For some reason whenever I import any external jar such as commons-net or ftp4j my app crashes on run. I have verified this by commenting out all lines that refer to the jars and the app runs properly.
I want to access data in a text file on an FTP server and print it out to a TextView. I have been stuck on this all day. How do I fix this? Permissions including in manifest are internet and external storage.
package com.testing.pack;
import java.io.BufferedInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.client.HttpClient;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class TestingActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
TextView tv;
Button go;
HttpClient client;
FTPClient ftp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tvTry);
Typeface face = Typeface.createFromAsset(getAssets(),
"Roboto-LightItalic.ttf");
tv.setTypeface(face);
go = (Button) findViewById(R.id.bGO);
go.setOnClickListener(this);
try {
//Attempt using commons-net
FTPClient ftpClient = new FTPClient();
ftpClient.connect("ftp://........./");
ftpClient.login(".......", ".....");
ftpClient.changeWorkingDirectory("......");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream(file));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("test.txt", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
//Attempt using ftp4j
//FTPClient ftp = new FTPClient();
//ftp.connect("........");
//ftp.login(".......", ".....");
//ftp.changeDirectoryUp();
//ftp.changeDirectory(".....");
//ftp.changeDirectory("public_ftp");
//ftp.download("test.txt", new java.io.File("....."));
} catch (Exception e) {
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getData ex = new getData();
try {
tv.setText(ex.getInternetData());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Are you using Eclipse to add the jars? Instead create a libs folder and copy the jars into it.
Here is a similar question: How can I use external JARs in an Android project?

Getting force close error in android when using threading

In my application i want to do bluetooth chat. I'm facing a problem in threading. In my application my android phone will work as server which has a blocking statement
socket=mServerSocket.accept();
for this purpose i've created a child thread so that it will run separately. But before finishing this child thread main thread goes down giving Force Close and if i use the .join() method it hangs up my UI.
What is the solution to run both threads parallel?
this is my code
main Activity
package com.my.bluechat_2_1;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class BlueChat extends Activity {
/** Called when the activity is first created. */
private BlueHandler btHandler=null;
private BluetoothAdapter btAdapter = null;
private Context context=this;
TextView chatWindow=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
chatWindow=(TextView)findViewById(R.id.textView1);
doStart();
}
private void doStart(){
Button btnStart=(Button)findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get local Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if(btAdapter == null)
{
Toast.makeText(context, "Device does not support Bluetooth", Toast.LENGTH_LONG).show();
}
if (!btAdapter.isEnabled()) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
chatWindow.append("Waiting for connection...\n");
btHandler=new BlueHandler(context,chatWindow,btAdapter);
Thread acceptThread=new Thread(btHandler);
acceptThread.start();
}
});
}
}
BlueHandler
package com.my.bluechat_2_1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class BlueHandler implements Runnable{
// Name for the SDP record when creating server socket
private static final String SMARTCAM_BT_SERVICE_NAME = "SmartCam";
// Unique UUID for this application
private static final UUID SMARTCAM_BT_SERVICE_UUID = UUID.fromString("95b82690-4c94-11e1-b86c-0800200c9a66");
private BluetoothAdapter btAdapter = null;
private BluetoothServerSocket btServerSocket = null;
private BluetoothSocket btSocket = null;
private InputStream btInputStream=null;
private Context contextObj=null;
private TextView textView;
public BlueHandler(Context contextObj,TextView textView,BluetoothAdapter btAdapter){
this.contextObj=contextObj;
this.btAdapter=btAdapter;
this.textView=textView;
try {
btServerSocket=this.btAdapter.listenUsingRfcommWithServiceRecord(SMARTCAM_BT_SERVICE_NAME, SMARTCAM_BT_SERVICE_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this.contextObj, "Service not created", Toast.LENGTH_LONG);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
textView.append("Inside child thread.\n");
textView.append(btServerSocket+"\n");
while (true) {
try {
btSocket = btServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (btSocket != null) {
// Do work to manage the connection (in a separate thread)
try {
btServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
textView.append("Connected.\n");
try {
btInputStream=btSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buffer = new byte[1024]; // buffer store for the stream
String s;
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes=btInputStream.read(buffer);
s= new String(buffer);
// Send the obtained bytes to the UI Activity
textView.append("received ::" +s+"\n");
} catch (IOException e) {
break;
}
}
}
}
You're probably getting a crash because you're accessing a textView on the worker thread. You'll need to use TextView.post(Runnable) to make that not happen.
In reality you should be using a bindable Service to do this kind of work. You can post back to the UI via broadcast intents or callback methods, That way you don't have to worry about rotation bugs.
Are you performing a long operation in the constructor of your children thread? Each long operation must be done in the run() method.

Categories

Resources