Question

hi every body im aymen and im student im creating an application who shows the image downloaded from ftp server which was token by the webcam
i wanna refresh the pic every 2 seconds but i didnt succeed even with one time plz help this is my code until now **mainActivity**

package com.pfe.ftpstreamer;

import java.io.FileOutputStream;

import com.pfe.ftpstreamer.R;
import com.pfe.ftpstreamer.MyFTPClient;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
private static final String TEMP_FILENAME = "test.txt";
private static final String TEMP_FILENAME1 = "cam.jpg";
private Context cntx = null;

MyFTPClient ftpclient = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    cntx = this.getBaseContext();

    View startButton = findViewById(R.id.button1);
    startButton.setOnClickListener(this);
    View stopButton = findViewById(R.id.button2);
    stopButton.setOnClickListener(this);
    View exitButton = findViewById(R.id.button3);
    exitButton.setOnClickListener(this);
 // Create a temporary file. You can use this to upload
    createDummyFile();
    ftpclient = new MyFTPClient();
}
public void onClick(View v) {
    switch(v.getId()) {
    case R.id.button1:
        new Thread(new Runnable() {
            public void run(){
                boolean status = false;
                // Replace your UID & PW here
                status = ftpclient.ftpConnect("192.168.1.1", "Administrator", "12345", 21);
                if (status == true) {
                    Log.d(TAG, "Connection Success");
                    status = ftpclient.ftpUpload(TEMP_FILENAME, TEMP_FILENAME, "/", cntx);
                    //downloading file
                    ftpclient.ftpDownload(TEMP_FILENAME1,getFilesDir() + "/" +TEMP_FILENAME1);
                    //removing the file from server 
                    ftpclient.ftpRemoveFile(TEMP_FILENAME1);
                    //showing the file in the ImageView
                    new Thread(new Runnable() {
                        public void run(){
                            ImageView imgView = (ImageView) findViewById(R.id.imageView1);
                            imgView.setImageBitmap(BitmapFactory.decodeFile(getFilesDir() + "/" +TEMP_FILENAME1));
                        }
                    }).start();



                } else {
                    //Toast.makeText(getApplicationContext(), "Connection failed", 2000).show();
                    Log.d(TAG, "Connection failed");
                }
            }
        }).start();
        break;  
    case R.id.button2:
        new Thread(new Runnable() {
            public void run(){
                ftpclient.ftpDisconnect();
            }
        }).start();

        break;
    case R.id.button3:
        this.finish();
        break;
    }

}

public void createDummyFile() {
    try {
        FileOutputStream fos;
        String file_content = "Hi this is a sample file to upload for android FTP client example";

        fos = openFileOutput(TEMP_FILENAME, MODE_PRIVATE);
        fos.write(file_content.getBytes());
        fos.close();

    } catch (Exception e) {
        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;
}}

*myftpclient**

package com.pfe.ftpstreamer;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.net.ftp.*;

import android.content.Context;
import android.util.Log;

public class MyFTPClient {



//Now, declare a public FTP client object.

private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null; 

//Method to connect to FTP server:
public boolean ftpConnect(String host, String username ,
                          String password, int port)
{
    try {
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
            // login using username & password
            boolean status = mFTPClient.login(username, password);

            /* Set File Transfer Mode
             *
             * To avoid corruption issue you must specified a correct
             * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
             * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
             * for transferring text, image, and compressed files.
             */
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            return status;
        }
    } catch(Exception e) {
        Log.d(TAG, "Error: could not connect to host " + host );
    }

    return false;
} 

//Method to disconnect from FTP server:

public boolean ftpDisconnect()
{
    try {
        mFTPClient.logout();
        mFTPClient.disconnect();
        return true;
    } catch (Exception e) {
        Log.d(TAG, "Error occurred while disconnecting from ftp server.");
    }

    return false;
} 

//Method to get current working directory:



//Method to change working directory:



//Method to list all files in a directory:



//Method to create new directory:



//Method to delete/remove a directory:



//Method to delete a file:

public boolean ftpRemoveFile(String filePath)
{
    try {
        boolean status = mFTPClient.deleteFile(filePath);
        return status;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
} 

//Method to rename a file:



//Method to download a file from FTP server:

/**
 * mFTPClient: FTP client connection object (see FTP connection example)
 * srcFilePath: path to the source file in FTP server
 * desFilePath: path to the destination file to be saved in sdcard
 */
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
    boolean status = false;
    try {
        FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
        status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
        desFileStream.close();

        return status;
    } catch (Exception e) {
        Log.d(TAG, "download failed");
    }

    return status;
} 

//Method to upload a file to FTP server:

/**
 * mFTPClient: FTP client connection object (see FTP connection example)
 * srcFilePath: source file path in sdcard
 * desFileName: file name to be stored in FTP server
 * desDirectory: directory path where the file should be upload to
 */
public boolean ftpUpload(String srcFilePath, String desFileName,
                         String desDirectory, Context context)
{
    boolean status = false;
    try {
       // FileInputStream srcFileStream = new FileInputStream(srcFilePath);

        FileInputStream srcFileStream = context.openFileInput(srcFilePath);

        // change working directory to the destination directory
        //if (ftpChangeDirectory(desDirectory)) {
            status = mFTPClient.storeFile(desFileName, srcFileStream);
        //}

        srcFileStream.close();
        return status;
    } 
    catch (Exception e) {
        Log.d(TAG, "upload failed: " + e);
    }

    return status;
}
}
Was it helpful?

Solution

You should check that image is downloaded or not, if its downloaded then you can update your UI in ui thread i.e.

mainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        ImageView imgView = (ImageView) findViewById(R.id.imageView1);
       imgView.setImageBitmap(BitmapFactory.decodeFile(getFilesDir() + "/" +TEMP_FILENAME1));
      }
}

OTHER TIPS

Ok, your problem is, that you are not in the UI-Thread.

You could use a AsyncTask or a Handler, which updates your view or layout.

Check this out: update-ui-from-thread

You can't update Your Ui direct from your thread use handler for that purpose check this link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top