Turn FTP command into ASync Task? - android

First off, don't flame me for not searching, I've looked for answers to this and while there are answers out there, I can't understand any of them.
Now, with that aside, I'm trying to put my ftp command into an ASync task for Android.
Code:
package com.dronnoc.ftp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;
import org.apache.commons.net.io.Util;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FTPTransfer ftp = new FTPTransfer("hostname", "user", "pass");
String data = Environment.getDataDirectory().toString();
data += "/data/com.dronnoc.ftp/databases/test.db";
boolean result = ftp.upload(data, "/ftp_dir/test.db");
if(result)
{
Log.d("message", "Upload Successful.");
}
else
{
Log.e("message", ftp.error());
}
ftp.close();
}
}
FTPTransfer.java
package com.dronnoc.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
public class FTPTransfer {
final FTPClient ftp = new FTPClient();
private String error = null;
private boolean connected = false;
public FTPTransfer(String host, String username, String pass) {
// TODO Auto-generated constructor stub
try {
ftp.connect(host);
if(ftp.login(username, pass))
{
ftp.enterLocalPassiveMode();
connected = true;
}
}
catch (FTPConnectionClosedException e) { error = e.getMessage(); }
catch (SocketException e) { error = e.getMessage(); }
catch (IOException e) { error = e.getMessage(); }
}
public boolean upload(String localName, String remoteName)
{
if(ftp.isConnected() && connected)
{
try {
FileInputStream file = new FileInputStream(localName);
boolean result = ftp.storeFile(remoteName, file);
if(result) { return true; }
else { return false; }
}
catch (FileNotFoundException e) { error = e.getMessage(); return false; }
catch (IOException e) { error = e.getMessage(); return false; }
}
return false;
}
public boolean upload(File localName, String remoteName)
{
if(ftp.isConnected() && connected)
{
try {
FileInputStream file = new FileInputStream(localName.getAbsolutePath());
boolean result = ftp.storeFile(remoteName, file);
if(result) { return true; }
else { return false; }
}
catch (FileNotFoundException e) { error = e.getMessage(); return false; }
catch (IOException e) { error = e.getMessage(); return false; }
}
return false;
}
public boolean download(String remote, String local)
{
//TODO Put appropriate code here
return false;
}
public boolean close()
{
try {
ftp.disconnect();
return true;
} catch (IOException e) {
error = e.getMessage();
return false;
}
}
public String error()
{
return error;
}
}
What I want to know is how I can put my FTP function into an ASync task so that I can run it in a background activity and update a progress bar, and also indicate how many bytes its uploaded so far?
Cheers
EDIT
The code itself works at the moment, I just need to know how to make it into an Async task

Not sure if you're asking how to use the AsyncTask but in case you are here's a tutorial about using AsyncTask to make requests to a web service. This can be extended easily to perform FTP in the background. AsyncTask can also support Progress though I don't think it's mentioned in the tutorial.
Basically your upload function needs to move to doInBackground and so does the connection code. See http://geekjamboree.wordpress.com/2011/11/22/asynctask-call-web-services-in-android/

Related

Socket For Android Emulator Works but Not For Real Device

I have java code that sends strings via ip to a python script. The code works perfectly with the emulator but when I successfully install the app via usb to my phone it does not work. Here is the code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_python = findViewById(R.id.python);
final Button btn_movie = findViewById(R.id.movie);
final Button btn_hw = findViewById(R.id.homework);
btn_python.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
send py = new send();
message = "python";
Log.i("Button", "Button works");
System.out.println("whatever");
py.execute();
}
});
btn_movie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
send mov = new send();
message = "movie";
mov.execute();
}
});
btn_hw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
send hw = new send();
message = "homework";
hw.execute();
}
});
}
class send extends AsyncTask<Void,Void,Void>{
Socket s;
PrintWriter pw;
#Override
protected Void doInBackground(Void...params) {
System.out.println("whatevernumbertwo");
try {
System.out.println("whatevernumberthree");
s = new Socket("ip address", 7800);
Log.i("Socket", "connects to socket");
pw = new PrintWriter(s.getOutputStream());
Log.i("output stream", "Output stream works");
pw.write(message);
Log.i("write", "Write works");
pw.flush();
Log.i("flush", "Flush works");
pw.close();
s.close();
} catch (UnknownHostException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
As I mentioned this works on the emulator but not on the actual device. The proper permissions have also been given. What am I doing wrong? Thanks in advance.
After much digging around, it turned out to be the server's firewall all along. That explains why (apparently) no exception was thrown, and why the code didn't seem to execute; it was executing, it was just getting stuck inside Socket() (during the connect).
Surely Socket() is, in fact, throwing an IOException; it probably just takes a while.
The code works on the emulator because, as it is operating on the same machine, it is behind the firewall.

Youtube upload videos programmatically

i have for the passed 4 days tried to upload to youtube videos but i have failed please help me .
package com.example.testyoutube;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaCategory;
import com.google.gdata.data.media.mediarss.MediaDescription;
import com.google.gdata.data.media.mediarss.MediaKeywords;
import com.google.gdata.data.media.mediarss.MediaTitle;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
public class MainActivity extends Activity {
private Button button;
private YouTubeService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitVideo("/storage/emulated/0/Pictures/Hello Camera/VID_20140523_204750.mp4",
"i have done it ", "Yooooooooo , it works", "fun");
}
});
}
public void submitVideo(String vName, String vTitle, String vDesc, String vCate) {
String developer_key = "api key"; // Registered developer key
String clientID = "gmailaccount"; // Server's Youtube account
String password = "passwordofgmailaccount"; // Server's Youtube password
service = new YouTubeService(clientID, developer_key); // YouTube Object, we take action by this.
try {
service.setUserCredentials(clientID,password);
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File videoFile = new File( vName ); // The video local file prepare to upload
String VIDEO_UPLOAD_FEED = "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
String mediaType = "video/*"; // Serach .flv MIME type may found more
String vKey1 = vCate; // Use same category and keyword
VideoEntry newEntry = new VideoEntry(); // YouTube video object type, they will return this after uploaded
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup(); // Collect all of the video information
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, vCate));
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(vTitle);
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent(vDesc);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword(vKey1);
MediaFileSource ms = new MediaFileSource(videoFile, mediaType);
newEntry.setMediaSource(ms);
VideoEntry ve = null;
try {
ve = service.insert(new URL(VIDEO_UPLOAD_FEED), newEntry);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ve == null){
System.out.println("Submit to youtube fail.");
return ;
}
}
}
it says that this "service = new YouTubeService(clientID, developer_key);" has error but it does not explain why , please help (or suggest another code please)
U can ddo it using Intent
ContentValues content = new ContentValues(4);
content.put(Video.VideoColumns.DATE_ADDED,
System.currentTimeMillis() / 1000);
content.put(Video.Media.MIME_TYPE, "video/mp4");
content.put(MediaStore.Video.Media.DATA, "video_path");
ContentResolver resolver = getBaseContext().getContentResolver();
Uri uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, content);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Title");
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(sharingIntent,"share:"));

Getting errors by using asmack configured jar from beem

So i have tried a lot the last days...
I built a XMPP Server and a Client for my pc without any problems.
Than i started to create a Client for Android and... yeah.. i just say i just dont want to read more errors..
I read all the things about bugs with XMPP, Android and PubSub. now i built this apk.
I am able to Connect and to stay online. My problem is a cannot build a Node.
So this is my Code:
`
package com.Eis.androidclient;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.PublishItem;
import org.jivesoftware.smackx.pubsub.SimplePayload;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Client extends Activity {
static {
XMPPConnection.DEBUG_ENABLED = true;
}
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"192.168.0.100", 5222);
XMPPConnection connection = new XMPPConnection(connConfig);
String pubSubAddress = "pubsub."+ connection.getServiceName();
PubSubManager manager = new PubSubManager(connection,pubSubAddress);
SimplePayload payload = new SimplePayload("session",
"pubsub:NewNode:session", "<sessionId>5678</sessionId>");
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>(null,
payload);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
org.jivesoftware.smack.SmackAndroid.init(this);
Button node = (Button)findViewById(R.id.button1);
node.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
node();
}
});
Thread thread = new Thread(){
public void run(){
try {
connection.connect();
connection.login("tester", "tester");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.run();
// putting null for id means you let server generate id
// you could use publish() for asynchronous call
}
public void node(){
PubSubManager manager = new PubSubManager(connection);
LeafNode myNode = null;
// manager.discoverNodes("NewNode");
try {
manager.getNode("NewNode");
System.out.println("found");
manager.deleteNode("NewNode");
System.out.println("delete");
} catch(XMPPException e){
System.out.println("nothing to do");
e.printStackTrace();
}
try{
myNode = manager.createNode("NewNode2");
System.out.println("created");
} catch (XMPPException e) {
System.out.println("nothing created");
e.printStackTrace();
}
// you could use publish() for asynchronous call
// try {
// myNode.send(item);
// System.out.println("versendet");
// } catch (XMPPException e) {
// System.out.println("wird nicht gesendet");
// e.printStackTrace();
// }
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
`
My App is running on a VM 2.3.3 so there shouldn't be any thread problems.
and here are the error logs
07:20:48 PM RCV (1079090656): <iq type="error" id="s1YUr-9" from="pubsub.nils-lappi" to="tester#nils-lappi/Smack"><pubsub xmlns="http://jabber.org/protocol/pubsub"><create node="NewNode2"/></pubsub><error code="409" type="cancel"><conflict xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>
so i dont know why there is a conflict but it seems the rest is ok
error code because of conflict:
at org.jivesoftware.smackx.pubsub.packet.SyncPacketSend.getReply(SyncPacketSend.java:53)
Hopefully someone here can help me...
The node NewNode2 already exists and you are trying to create it again.
NOTE: You can simplify your creation of the PubsubManager to just
new PubsubManager(connection);
The usage of pubsub as the service name is actually the default.

Android Socket Getting Hanged

I have Created a Service Which in turn Creates a Socket, But as soon as try to read data sent from Server, it hangs ,On the other hand the same code run if i am not using Service but plain Activity ??
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import java.net.*;
import java.io.*;
import android.widget.*;
public class BackgroundService extends Service
{
private Socket socket=null;
private InputStreamReader in=null;
private String ip;
private String tag="BackgroundService";
public IBinder onBind(Intent p1)
{
// TODO: Implement this method
return null;
}
public void onCreate(){
super.onCreate();
}
public void onStart(Intent i,int id){
super.onStart(i,id);
ip=i.getStringExtra("Ip");
Log.v(tag,"Ip "+i.getStringExtra("Ip"));
try
{
socket = new Socket(ip.trim(), 8888);
new Runnable() {
public void run()
{
// Hangs in this block.....
try
{
in = new InputStreamReader (socket.getInputStream());
BufferedReader bf=new BufferedReader (in);
// Never Reaches this messge
Log.v(tag,"mess:"+bf.readLine() );
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.run();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Log.v is the Problem it wont allow you print the value so use System.out.println() and bf.printline will contain the message

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