Android file upload using ftp - android

Android file upload not working and not showing any error or any exception.
I want to add up some thing like check the internet connection when it is working only then it tries to upload the file and also want to add up one more thing that it makes a sync between server and application that this code will be called automatically after regular interval of time when the internet connection is working.
I have tried many jar files to upload the file and make an ftp connection but nothing works. jar file link http://www.jibble.org/files/simpleftp.jar
import org.jibble.simpleftp.SimpleFTP;
File file = new File("/sdcard/CreativeDroid/test.txt");
this way I am calling MyAsyncTask class to upload a txt file
new MyAsyncTask().execute(file.toString());
private class MyAsyncTask extends AsyncTask <String, Integer, Double> {
protected Double doInBackground(String... params) {
try {
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("www.creativetabs.co", 21, "username", "password");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
//ftp.cwd("web");
// Upload some files.
ftp.stor(new File(params[0]));
// Quit from the FTP server.
ftp.disconnect();
} catch (IOException e) {
Log.d("error", e.toString());
// TODO Auto-generated catch block
}
return null;
}
}

Try using ftp4j:
http://www.sauronsoftware.it/projects/ftp4j/
I have been using this since 3 years and it works flawless.
private int uploadFile() throws Exception {
long fileSize = 0;
boolean supported = ftp.isResumeSupported();
String fileName = getFileName(file_path);
String server_path = data.getServer_folder() + fileName;
try {
fileSize = ftp.fileSize(server_path);
} catch (Exception e) {
fileSize = 0;
}
if (fileSize == 0) {
ftp.upload(new java.io.File(file_path), new FTPDataTransferListener() {
#Override
public void transferred(int arg0) {
uploaded = uploaded + arg0;
Utilities.showDLog(Tag, "uploaded: " + uploaded);
}
#Override
public void started() {
Utilities.showDLog(Tag, "uplaod started");
}
#Override
public void failed() {
Utilities.showDLog(Tag, "upload failed");
disconnectFTP();
outputCode = FTPOutputCodes.FAILED;
}
#Override
public void completed() {
outputCode = FTPOutputCodes.SUCCESSFULLY_UPLOADED;
Utilities.showDLog(Tag, "upload completed");
}
#Override
public void aborted() {
outputCode = FTPOutputCodes.ABORTED;
disconnectFTP();
Utilities.showDLog(Tag, "upload aborted");
}
});
} else if (supported) { // resume file upload
ftp.upload(new java.io.File(file_path), fileSize, new FTPDataTransferListener() {
#Override
public void transferred(int arg0) {
Utilities.showDLog(Tag, "Resume data transfered: " + arg0);
}
#Override
public void started() {
Utilities.showDLog(Tag, "Resume started");
}
#Override
public void failed() {
outputCode = FTPOutputCodes.FAILED;
disconnectFTP();
Utilities.showDLog(Tag, "Resume failed");
}
#Override
public void completed() {
outputCode = FTPOutputCodes.SUCCESSFULLY_UPLOADED;
}
#Override
public void aborted() {
outputCode = FTPOutputCodes.ABORTED;
disconnectFTP();
Utilities.showDLog(Tag, "resume aborted");
}
});
}
return outputCode;
}
protected void disconnectFTP() {
try {
ftp.disconnect(true);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
e.printStackTrace();
} catch (FTPException e) {
e.printStackTrace();
}
}

Related

Volley or Fast Networking does not download the whole file (corrupted file) in specific link

I have codes that download file from api.
I get a problem when the url I give is like "http://blalba.towert.win/core/me/service.php?class=awin%2Fcore%2Fmod%2Fresource%2Fview.php%3Fid%3D5&id=3" I got corrupt file.
but when using the direct link from the dropbox like
https://www.dropbox.com/s/b5v2asdasd9bly663qr/thisFile.pdf?dl=1
can be downloaded properly without corrupt.
how I can download properly with that first link ?
my Fast Networking code :
new FastNetworkingUtils().FNRequestDownloadAPKFile(activity, url, txtPathUserData, pdfName, TAG_DOWNLOAD_PDF, dialog, new InterfaceFastNetworkingDownloadFile() {
#Override
public void onProgress(final long bytesDownloaded, final long totalBytes) {
// do anything with progress
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
double precentage = ((double) bytesDownloaded / (double) totalBytes) * 100;
// progressD.setProgress((int) precentage);
}
});
}
#Override
public void onDownloadComplete() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
String txtPath = txtPathUserData + pdfName+".pdf";
try {
File file = new File(txtPath);
Uri uri = FileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
IntentCustom.intentPDViewer(activity, uri, true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onError(ANError error) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
});
my Volley Code :
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response!=null) {
String path = txtPathUserData + pdfName+".pdf";
FileOutputStream stream = new FileOutputStream(path);
stream.write(response);
try {
File file = new File(path);
Uri uri = FileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
IntentCustom.intentPDViewer(activity, uri, true);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(context, "Download complete.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
} ,new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(context, new HurlStack());
mRequestQueue.add(request);

How to send and receive image through using ServerSocket Service?

I am trying to sending and receiving image to display in ImageView using Server-socket, I want to decrypt image using server-socket but its not working.
Image url like this :
http://localhost:4545/sdcard0/emulated/test.img;
Service :
public class ImageDecrptService extends Service {
private ServerSocket serverSocket;
private Socket socket;
void acceptRequestNDecryptFile() {
try {
try {
serverSocket = new ServerSocket(4545);
} catch (Exception e) {
}
while (true) {
Log.e("", "thread called true");
socket = serverSocket.accept();
//some thing code
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
acceptRequestNDecryptFile();
Log.e("", "thread called ");
} catch (Exception e) {
e.printStackTrace();
}
}
});
#Override
public void onCreate() {
super.onCreate();
try {
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
How can pass image url to server socket?
Note : I do not want use Bitmap to display image.
If you have a http url of an image on a webserver then you would need a client to grab the image.
So your ServerSocket is of no use.
Also a client-Socket would not be the right way to go.
You need to use a http component or library to download the image.
Or invoke the DownloadManager.

How to know the reachable of any url address?

I wrote the following method to know the reachable of url.
public boolean isMyURLReachable(String url){
boolean reachable = false;
try {
reachable = InetAddress.getByName(url).isReachable(2000);
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return reachable;
}
and I call it like that.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
boolean reachable = isMyURLReachable("www.google.com");
if(reachable)
Toast.makeText(getApplicationContext(), "Reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "Unreachable", 500).show();
}
});
But android.os.NetworkMainThreadException occur, do I need anything to put in my androidmanifest.xml file or my idea is being wrong?
NetworkMainThreadException is thrown when an application attempts to perform a networking operation on its main thread.
Please try to perform that in an AysncTask or another thread.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
I wrote the following inner class.
class URLCheckTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... url) {
boolean reachable = false;
try {
reachable = InetAddress.getByName(url[0]).isReachable(7000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(reachable)
return "1";
else
return "0";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("1"))
Toast.makeText(getApplicationContext(), "reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "unreachable", 500).show();
}
}
and call it from onClick() method.
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new URLCheckTask().execute("www.google.com");
}
});
No exception occur this time. But...., the result is not correct even though I can call it from emulator's browser, it always show me unreachable.

Add Data to post on facebook wall in android not displaying any message to post

I am using the following code and trying to post message on facebook wall along with the picture url. Both message and picture url is empty. Can any one find out and direct me in the right direction?
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
public void postToWall() {
Bundle params = new Bundle();
params.putString("message","test to post");
params.putString("url", URLEncoder.encode("http://a.espncdn.com/photo/2010/0523/pg2_a_cricket_576.jpg"));
try {
String response = facebook.request("me/feed", params, "POST");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
set this permission as public
private String[] PERMISSIONS = new String[]
{ "publish_stream", "read_stream", "offline_access" };
This will check is session exist if yes then it will direct update if not then ask user permission to update on wall.
Button click event
facebookConnector = new FacebookConnector(APP_ID, activity.getParent(),
activity.getApplicationContext(),PERMISSIONS);
if (facebookConnector.getFacebook().isSessionValid())
{
postMessageInThread(position); // see method below
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
#Override
public void onAuthSucceed()
{
postMessageInThread(position);
}
#Override
public void onAuthFail(String error)
{
}
};
SessionEvents.addAuthListener(listener);
facebookConnector.login();
}
This will update your data on wall
private void postMessageInThread(final int position)
{
Thread t = new Thread()
{
public void run()
{
try
{
facebookConnector.postMessageOnWall(
"Your Text Data",
"Your Email URL","Description");
mFacebookHandler.post(mUpdateFacebookNotification);
} catch (Exception ex)
{
Log.e("", "Error sending msg", ex);
}
}
};
t.start();
}
Note: : Here Position is my list record so manage your data according to that.

Loading Multiple Audio files from SD card

I need help/pointer to doc/sample code on how to load multiple audio files from a specific folder on the SD card and have it play a random file back(i think i can figure out the last step if i could just figure out how to load multiple files). Here is my incredibly poorly written app so far, don't judge too harshly as I'm learning as I go.
public class zazenbox extends Activity implements OnClickListener{
File filecheck;
MediaPlayer player;
Button playerButton;
Integer var1;
String path1;
AlertDialog.Builder alertbox;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
demoLoad();
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop);
playerButton.setOnClickListener(this);
demoPlay();
}
#Override
public void onPause() {
super.onPause();
player.pause();
}
#Override
public void onStop() {
super.onStop();
player.stop();
}
private void demoLoad() {
dirfilecheck();
player = new MediaPlayer();
player.setLooping(true);
try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }
}
private void dirfilecheck() {
filecheck = new File(Environment.getExternalStorageDirectory() + "/zazenbox");
if(filecheck.exists() && filecheck.isDirectory()) {
// load files.
var1 = 1;
path1 = filecheck + "/bm10" + var1 + ".wav";
} else {
// create folder, dl sample loop, and instruct user how to add music/loops.
filecheck.mkdirs();
alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Please put loopable media in zazenbox on your sdcard.");
alertbox.setNeutralButton("Ok, I will.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "Please plug in your device now", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
}
}
private void demoPause() {
player.pause();
playerButton.setText(R.string.play);
}
private void demoStop() {
player.stop();
playerButton.setText(R.string.play);
}
private void demoPlay() {
player.start();
playerButton.setText(R.string.stop);
}
private void playPause() {
if(player.isPlaying()) {
demoStop();
//demoPause();
//player.release();
var1++;
path1 = filecheck + "/bm10" + var1 + ".wav";
/*try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }*/
//player.start();
//demoPlay();
} else {
//do stuff
demoPlay();
}
}
}
Memory is extremely limited on mobile devices, so you wouldn't want to load songs you're not going to play. So what you should do is find all of the audio files in that folder, and then choose one and THEN load and play it.
You just need to stop the current player and create a new instance.
MediaPlayer player = MediaPlayer.create(this, Uri.parse("Path/To/Media"));
player.start();
// change track
player.stop();
player = MediaPlayer.create(this, Uri.parse("New/Path/To/Media"));
player.start();

Categories

Resources