Android FTP DownLoad Progressbar - java

FTP code, but only the download...
public class ImageUploadTask extends AsyncTask <String, Void, String>{
String e;
protected String doInBackground(String...args) {
String strResponce = "";
ftpClient = new FTPClient();
s="finish";
try {
ftpClient.connect(InetAddress.getByName(SERVER));
ftpClient.login(USERNAME, PASSWORD);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
textTargetUri.setText("good");
final String remote = "/1.jpg";//FTP adress/filename
String savefilepath = "/sdcard/download"+remote;
File downloadfile = new File(savefilepath);//download
local = new FileOutputStream(downloadfile);
ftpClient.retrieveFile(remote, local);
local.close();
ftpClient.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
}
return s;
}
}
BUT!! FTP DownLoad code do insert CountingOutputStream function.
CountingOutputStream function is commons-io-2.4.jar.
project in commons-io-2.4.jar and commons-net-3.3.jar to there. T_T
public class ImageUploadTask extends AsyncTask <String, Void, String>{
String e;
protected String doInBackground(String...args) {
String strResponce = "";
ftpClient = new FTPClient();
s="finish";
try {
ftpClient.connect(InetAddress.getByName(SERVER));
ftpClient.login(USERNAME, PASSWORD);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
textTargetUri.setText("good");
final String remote = "/1.jpg";//FTP adress/filename
String savefilepath = "/sdcard/download"+remote;
File downloadfile = new File(savefilepath);//download
local = new FileOutputStream(downloadfile);
long fileSize = 0;
FTPFile[] files = ftpClient.listFiles(remote);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
String a = String.valueOf(fileSize);
Log.d("File Size", a);
}
CountingOutputStream cos = new CountingOutputStream(local) {
protected void beforeWrite(int n) {
super.beforeWrite(n);
int progress = Math.round((getCount() * 100) / 879394);
//String b = String.valueOf(progress);
//Log.d("File persent", b);
}
};
ftpClient.retrieveFile(remote, cos);
local.close();
ftpClient.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
}
return s;
}
}
What's wrong with the code, I do not know how?
code no error.
but APP start error.

In a background tread (such as in doInBackGround()) no UI elements can be changed at all. If in activity use runOnUiThread or else use textTargetUri.post. This way the setText part takes place on the UI thread as needed.

Related

Slower Java Asynchronous Client run after about one hour

I tried to connect with asynchronous socket and read new messages once per second.
I used sample client code (http://www.java2s.com/Tutorials/Java/Java_Network/0080__Java_Network_Asynchronous_Socket_Channels.htm) and in getTextFromUser method I added sleep method (with 1000 ms) and removed read command from user.
Additionally I added additional logic in ReadWriteHandler method. It started work great, but after about one hour program was suspended and has worked (execute my additional logic) not once per second but one per about 10 minutes.
Do you have any idea what might happen?
Part of code:
public void ConnectAsynchr() {
try {
this.channel = AsynchronousSocketChannel.open();
SocketAddress serverAddr = new InetSocketAddress("localhost", PortNumberAsynchr);
Future<Void> result = channel.connect(serverAddr);
try {
result.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.writeLog("ConnAsynch", "Asynchronous connection succesful established", true);
this.connectAsynch = true;
this.attach = new Attachment();
this.attach.channel = this.channel;
this.attach.buffer = ByteBuffer.allocate(16384);
this.attach.isRead = false;
this.attach.mainThread = Thread.currentThread();
ReadWriteHandler readWriteHandler = new ReadWriteHandler();
this.channel.write(this.attach.buffer, this.attach, readWriteHandler);
try {
this.attach.mainThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
this.writeLog("ERROR", e.toString(), false);
e.printStackTrace();
}
}
catch (IOException e) {
this.writeLog("ERROR", e.toString(), false);
System.out.println(e);
}
}
class Attachment {
AsynchronousSocketChannel channel;
ByteBuffer buffer;
Thread mainThread;
boolean isRead;
}
class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
#Override
public void completed(Integer result, Attachment attach) {
if (attach.isRead) {
attach.buffer.flip();
Charset cs = Charset.forName("UTF-8");
int limits = attach.buffer.limit();
byte bytes[] = new byte[limits];
attach.buffer.get(bytes, 0, limits);
String msg = new String(bytes, cs);
writeLog("Asynchr Msg rec", msg, false);
AsynchrMessLogic(msg);
try {
msg = this.getTextFromUser();
} catch (Exception e) {
e.printStackTrace();
}
if (msg.equalsIgnoreCase("bye")) {
attach.mainThread.interrupt();
return;
}
attach.buffer.clear();
byte[] data = msg.getBytes(cs);
attach.buffer.put(data);
attach.buffer.flip();
attach.isRead = false; // It is a write
attach.channel.write(attach.buffer, attach, this);
}else {
attach.isRead = true;
attach.buffer.clear();
attach.channel.read(attach.buffer, attach, this);
}
}
#Override
public void failed(Throwable e, Attachment attach) {
e.printStackTrace();
}
private String getTextFromUser() throws Exception{
/*System.out.print("\nPlease enter a message (Bye to quit):");
BufferedReader consoleReader = new BufferedReader(
new InputStreamReader(System.in));
String msg = consoleReader.readLine();
*/
Thread.sleep(threadSleep);
String msg="aaa";
return msg;
}
}

Get Tweets from Twitter hbc API

public class TwitterStreamImpl implements TwitterStream {
public void setUpStream() throws InterruptedException {
final String consumerKey = getTwitterCredentials().get(0).toString();
final String consumerSecret = getTwitterCredentials().get(1).toString();
final String token = getTwitterCredentials().get(2).toString();
final String secret = getTwitterCredentials().get(3).toString();
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
// add some track terms
endpoint.trackTerms(Lists.newArrayList("twitterapi", "#yolo", "trump", "donald", "lol"));
Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
// Authentication auth = new BasicAuth(username, password);
// Create a new BasicClient. By default gzip is enabled.
BasicClient client = new ClientBuilder()
.hosts(Constants.STREAM_HOST)
.endpoint(endpoint)
.authentication(auth)
.processor(new StringDelimitedProcessor(queue))
.build();
// Establish a connection
client.connect();
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 1000; msgRead++) {
if (client.isDone()) {
System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
break;
}
String msg = queue.poll(5, TimeUnit.SECONDS);
if (msg == null) {
System.out.println("Did not receive a message in 5 seconds");
} else {
System.out.println(msg);
}
}
client.stop();
}
/**
* Reads twitterStup.txt from C:/Users/"user"/documents/ and returns them as
* an array
*
* #return Twitter Api Credentials
*/
private ArrayList getTwitterCredentials() {
BufferedReader in;
String str;
ArrayList<String> list = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("*******"));
while ((str = in.readLine()) != null) {
list.add(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
The console log says:
Did not receive a message in 5 seconds
And it says that every five seconds.
I want to "sysout" (live) every tweet, that has one of the endpoint trackTerms in it. But there is no error or something similar.
Is there a problem with the proxy perhaps?
The code is working, as it is at the time. The problem was the proxy. Because I've been in the office-network, the connection to the stream wasn't possible. So i tried it with my own notebook, guess what, it worked.

Error when logging into FTP from AsyncTask class using org.apache.commons.net.ftp.FTPClient

I am logging into the ftp account using AsyncTask but I keep getting this error,
12-31 15:26:19.637: E/dalvikvm(5986): Could not find class 'org.apache.commons.net.ftp.FTPClient', referenced from method com.example.testme.Processing.connnectingwithFTP
I can understand that my method inside Asynctask is not able to find the FTPClient class eventhough it is imported fine. But I don't how to make my inner AsyncTask method find the FTPClient class.
Here is my code,
AsyncTask class
class Processing extends AsyncTask<Object, Void, Void> {
#Override
protected Void doInBackground(Object... params) {
connnectingwithFTP("host", "username",
"password");
return null;
}
public void connnectingwithFTP(String ip, String userName, String pass) {
boolean status = false;
try {
FTPClient mFtpClient = new FTPClient();
mFtpClient.setConnectTimeout(10 * 1000);
mFtpClient.connect(InetAddress.getByName(ip));
status = mFtpClient.login(userName, pass);
Log.e("isFTPConnected", String.valueOf(status));
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
mFtpClient.setFileType(FTP.ASCII_FILE_TYPE);
mFtpClient.enterLocalPassiveMode();
FTPFile[] mFileArray = mFtpClient.listFiles();
Log.e("Size", String.valueOf(mFileArray.length));
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is what I am doing in onCreate method,
Processing p1 = new Processing();
p1.execute();
You should add the jar file to the libs folder of your project. Also, make sure it's checked under the Order and Export tab.

Android:NetworkOnMainThreadException error inside AsyncTask

okay so i created a inner class which extends AsycTask in order for my code to run outwith the UI thread. However i'm getting this error so i assume this means some part of my onPostExecute needs to be done in doInBackground however i cant figure out exactly what this is
public class asyncTask extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);
#Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.setMessage("loading...");
dialog.show();
}
#Override
protected String doInBackground(String...parmans){
{
for(int i = 0; i < 100; i++){
publishProgress(1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String urlString = petrolPriceURL;
String result = "";
InputStream anInStream = null;
int response = -1;
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
return null;
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
// Check that the connection can be opened
if (!(conn instanceof HttpURLConnection))
try {
throw new IOException("Not an HTTP connection");
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
try
{
// Open connection
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
// Check that connection is OK
if (response == HttpURLConnection.HTTP_OK)
{
// Connection is OK so open a reader
anInStream = httpConn.getInputStream();
InputStreamReader in= new InputStreamReader(anInStream);
BufferedReader bin= new BufferedReader(in);
// Read in the data from the RSS stream
String line = new String();
while (( (line = bin.readLine())) != null)
{
result = result + "\n" + line;
}
}
}
catch (IOException ex)
{
try {
throw new IOException("Error connecting");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
#Override
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// Get the data from the RSS stream as a string
errorText = (TextView)findViewById(R.id.error);
response = (TextView)findViewById(R.id.title);
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
catch(Exception ae)
{
// Handle error
errorText.setText("Error");
// Add error info to log for diagnostics
errorText.setText(ae.toString());
}
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
}
if someone could point out my error as well as show an example of where the code is suppose to go in my doInBackground that would be great. Thanks
problem:
result = doInBackground(petrolPriceURL);
you are implicitly calling the doInbackground method in the onPostExecute which will actually run in your UI thread instead on a different thread thus resulting to Android:NetworkOnMainThreadException.
Also it is unnecessary to call doInBackground that it is already executed before onPostExecute when you execute your Asynctask. Just directly use the result parameter of the onPostExecute.
sample:
#Override
protected void onPostExecute(String result) {
// Get the data from the RSS stream as a string
errorText = (TextView)findViewById(R.id.error);
response = (TextView)findViewById(R.id.title);
response.setText(result);
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
I suspect the error is related to this part of your code:
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
doInBackgound is called automatically when you call asynctask.execute. To start your task correctly you should (1) create a new instance of your task; (2) pass the string params you need to use in doInBackground in the execute method; (3) use them; (4) return the result to onPostExecute.
For Example:
//in your activity or fragment
MyTask postTask = new MyTask();
postTask.execute(value1, value2, value3);
//in your async task
#Override
protected String doInBackground(String... params){
//extract values
String value1 = params[0];
String value2 = params[1];
String value3 = params[2];
// do some work and return result
return value1 + value2;
}
#Override
protected void onPostExecute(String result){
//use the result you returned from you doInBackground method
}
You should try to do all of your "work" in the doInBackground method. Reutrn the result you want to use on the main/UI thread. This will automaticlly be passed as an argument to the onPostExecute method (which runs on the main/UI thread).

making a Curtom class from a custom function

I'm new to Android development and i am trying to make a custom class which I can access in my activities to read text from files on a server. i have a custom function which works fine but i need to access this function in many activities so i need a custom class which performs the same action. My function is here
public String GetLinkss(String url) {
String StringBuffer="";
String stringText="";
try {
URL link = new URL(url);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(link.openStream()));
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stringText;
}
Create a package like this:
package com.whatever.utils;
public class Utils {
private Context mContext;
// constructor
public Utils(Context activityContext) {
mContext = activityContext;
}
public static String GetLinkss(String url) {
// your stuff
}
// other functions/methods used throughout the application
}
And then you use it like this wherever you want:
String myStringText = Utils.GetLinkss("my_url");
HTH

Categories