Error updating photo from Android to FTP - android

I follow one manual to upload images from Android to FTP. If I try to update a photo that have taken I can't see anything on the FTP file. It creates and the size is ok, but contains nothing. Then i try to upload one little image and this is the result:
(Random image to upload)
(Image uploaded)
The code: `class Sender extends AsyncTask
{
File photo;
public Sender(File photo){
this.photo=photo;
}
protected String doInBackground(String... params)
{
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("ftp.fercode.com"));
ftpClient.login(xxx","xxx");
Boolean result = ftpClient.changeWorkingDirectory("/img");
Log.e("existeix carpeta?",result.toString() );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream srcFileStream=null;
try {
srcFileStream = new FileInputStream(photo.getAbsolutePath());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//ftpClient.stor(photo.getAbsolutePath());
boolean status = ftpClient.storeFile("/img/imagePrueba.jpeg",
srcFileStream);
Log.e("Status", String.valueOf(status));
srcFileStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}`
What I'm doing wrong? Thx a lot

That happens because I upload the image like ASCII and not binary. It's just a configuration parameter:
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

Related

What is reason for adding processDialog in async task slow down it?

This is an issue in proccess dialog in async task
I search a lot for finding the reason of proccessDialog in Async task is SlowDown speed of what you put in doInBackground.
Can anyone say why its occuring...
Below is my code
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Asycdialog = new ProgressDialog(Server_connection.this);
Asycdialog.setMessage("Checking Connection.......");
Asycdialog.setCanceledOnTouchOutside(false);
Asycdialog.show();
field_res_partner = mf.fields_res_partner();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OVersionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
sync_data_server.Search_read(Server_connection.this, "res.partner",
field_res_partner);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Asycdialog.dismiss();
// Intent intent = new Intent(Server_connection.this,
// SplashMenu.class);
// startActivity(intent);
}
use
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
to update your progress and :
publishProgress (Progress... values)
to send updating status to the progress
here

Android App Async Failing to load internal data

I'm currently learning about IO and Async but am having issues. I'm following a guide, and according to the guide this is supposed to work. I have created an activity with a simple EditText, TextView, and 2 Buttons(save and load). I am trying to have the save button take the text in the EditText and save to internal storage, and the load button take whatever is saved and set the TextView as that. Everything works flawlessly when I put all the code to run in the UI thread, but if I change the code to have the UI thread call the Async class for the loading, nothing seems to happen.
**Packages and imports have been removed to save space.
public class InternalData extends Activity implements OnClickListener {
EditText etSharedData;
TextView tvDataResults;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
}
private void setupVariables() {
Button bSave = (Button) findViewById(R.id.bSave);
Button bLoad = (Button) findViewById(R.id.bLoad);
etSharedData = (EditText) findViewById(R.id.etSharedPrefs);
tvDataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
bSave.setOnClickListener(this);
bLoad.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
String sData = etSharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(sData.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fis.close();
tvDataResults.setText(sCollected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
The previous code makes everything work, but the UI lags a bit when trying to load large strings. When I try to have an LoadSomeStuff(Async) class do the loading, it does absolutely nothing when I hit Load on my phone. Within the LoadSomeStuff class it has the doInBackground method open the file and read the data into a string then return that string, and the onPostExecute method set the TextView's text to the returned String. Here's the code:
The onClick method for load button has:
new LoadSomeStuff().execute(FILENAME);
LoadSomeStuff Class *Note: This class is declared within the InternalData class.
public class LoadSomeStuff extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fis.close();
return sCollected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
tvDataResults.setText(result);
}
}
}
Any help is greatly appreciated, thanks!
It actually looks like I had an extra method or two(like onPreExecute) with no code in them and when I deleted them it starting working.

Apache commons ftpclient not connecting

I am writing an application to download files from ftp server. The code exits with error - UnknownHostException. The site is valid and I have opened it in filezilla. The code follows -
public class Downloader extends AsyncTask<String, Integer, String> {
private FTPClient mFtp;
private FTPFile[] files;
public Downloader() {
mFtp=new FTPClient();
try {
mFtp.connect(InetAddress.getByName("fenils.in"));
// mFtp.connect("ftp://fenils.in");
mFtp.login("*****", "******");
mFtp.setFileType(FTP.BINARY_FILE_TYPE);
mFtp.enterLocalPassiveMode();
files=mFtp.listFiles("/pankaj/beta");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... arg0) {
FileOutputStream fos = null;
try {
for(FTPFile f:files){
fos=new FileOutputStream("alpha/"+f.getName());
mFtp.retrieveFile(f.getName(), fos);
}
fos.close();
mFtp.logout();
mFtp.disconnect();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Any help is appreciated. Thanks in advance.
Sorry. My mistake. I neglected to set the uses internet permission. I found the answer here Java ftpclient application doesn't connect

Reading FTP File with Android

I am using FTP to upload a file. This works great. This file contains information what the app should do.
So I am doing the following:
1) Download the file with Apache FTP Client (seems to work fine)
2) Try to read out the file with a BufferedReader and FileReader.
The problem:
I get a NullPointerException while reading the file. I guess that this is a timing problem.
The code has this structure:
...
getFile().execute();
BufferedReader br = new BufferedReader(...);
How can I solve this problem?
I have to use a seperate Thread (AsyncTask) to download the file because otherwise it will throw a NetworkOnMainThread Exception.
But how can I wait until the file is completely downloaded without freezing the UI?
I cannot use the BufferedReader inside AsyncTask because I use GUI elements and I have to run the interactions on the GUI Thread, but I have no access to it from AsyncTask. RunOnUiThread does not work as well because I am inside a BroadcastReceiver.
Some code:
private class GetTask extends AsyncTask{
public GetTask(){
}
#Override
protected Object doInBackground(Object... arg0) {
FTPClient client = new FTPClient();
try {
client.connect("*****");
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
client.login("*****", "*****");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream( "/sdcard/"+userID+".task" );
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
resultOk &= client.retrieveFile( userID+".task", fos );
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}/**
try {
client.deleteFile(userID+".task");
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
**/
try {
client.disconnect();
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
return null;
}
}
The Broadcastreceiver class:
public class LiveAction extends BroadcastReceiver {
...
private Context cont;
FileReader fr = null;
BufferedReader br;
#Override
public void onReceive(Context context, Intent intent)
{
cont = context;
...
new GetTask().execute();
try {
Thread.sleep(3000);
}
catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fr = new FileReader("/sdcard/"+userID+".task");
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
br = new BufferedReader(fr)
String strline = "";
try {
while ((strline = br.readLine()) != null){
if(strline.equals("taskone")){
//Some GUI Tasks
}
....
This is the relevant code.
I think the best approach would be to read the file's contents from the doInBackground inside the AsyncTask and then output an object which contains the info you need on the onPostExecute method of the async stask and then manipulate your UI.
private AsyncTask<String,Void,FileInfo> getFile(){
return new AsyncTask<String,Void,FileInfo>{
protected FileInfo doInBackground(String url){
FileInfo finfo = new FileInfo(); // FileInfo is a custom object that you need to define that has all the stuff that you need from the file you just downloaded
// Fill the custom file info object with the stuff you need from the file
return finfo;
}
protected void onPostExecute(FileInfo finfo) {
// Manipulate UI with contents of file info
}
};
}
getFile().execute();
Another option is to call another AsyncTask from onPostExecute that does the file parsing but I would not recommend it
I would try some thing like this:
private class GetTask extends AsyncTask{
LiveAction liveAction;
public GetTask(LiveAction liveAction){
this.liveAction = liveAction;
}
...
#Override
protected void onPostExecute(String result) {
liveAction.heyImDoneWithdownloading();
}
}
Ps: why the Thread.sleep(5000)?
public class LiveAction extends BroadcastReceiver {
...
public void heyImDoneWithdownloading(){
//all the things you want to do on the ui thread
}
}

android 4.1 image reading from url

Hi I am trying to get an image from url to bitmap. I have android 4.1 device. When I run this code on new URL(). open connection().getInputStream()); app freezes then force close. Any idea?
runOnUiThread(new Runnable() {
public void run() {
String url = "http://netmera.com/cdn/app/file/netmera.com/series/img-48/1372262272227_89/medium";
try {
Bitmap bmp = BitmapFactory.decodeStream(new URL(url)
.openConnection().getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You are running network related operation on the ui thread using runOnUiThread.
You should use a Thread or use Asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
You are probably getting NetworkOnMainThreadException
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
Load asynctask on ui thread.
new TheTask().execute().
AsyncTask
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "http://netmera.com/cdn/app/file/netmera.com/series/img-48/1372262272227_89/medium";
try {
Bitmap bmp = BitmapFactory.decodeStream(new URL(url)
.openConnection().getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
Use runOnUiThread to update ui and do your netowrk related operation in doInbackground().
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
// update ui
}
});
bitmap = BitmapFactory.decodeStream((InputStream) new URL("your url").getContent());
The reason for the Crash can be two things
Network operation should not be done on the UI thread. Kindly use AsyncTask for this. //NetworkOnMainThreadException
Do not use strong referneces for Bitmaps. Use WeakReference<Bitmap> objects //OutOfMemoryException
I am doing it like this
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==1){
doctoImage.setImageBitmap(bitmap);// doctoImage you image view
}
}
};
Thread thread = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
doctor.getPhoto()).getContent());
handler.sendEmptyMessage(1);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});thread.start();

Categories

Resources