all is it possible to create a progress dialog to show the upload progress under a thread i use this code to upload a file called index.html to ftp.
please help me thanx in advance..
new Thread(new Runnable() {
public void run() {
Looper.prepare();
FTPClient client = new FTPClient();
try {
boolean result = false;
FileInputStream fis = null;
client.connect(server);
client.enterLocalPassiveMode();
client.login(user, pass);
client.makeDirectory("/public_html/"+str);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.setFileTransferMode(FTP.BINARY_FILE_TYPE );
client.changeWorkingDirectory(str);
String path1 = Environment.getExternalStorageDirectory() + "/index.htm";
File f = new File(path1);
String testname = "/public_html/"+str+"/"+f.getName();
fis = new
FileInputStream(f);
result = client.storeFile(testname, fis);
if (result == true){
Log.v("upload","upload successfull");
}
else{
Log.v("upload", "upload failed");
}
client.logout();
client.disconnect();
}
catch (Exception e) {
Context context = getApplicationContext();
CharSequence text = "failed!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}).start();
Why not use an asynctask? With it you could spawn a dialog in the onPreExecute method than in the onProgressUpdate method update the progress of the background task...There are other ways of doing it but i believe this to be the cleanest and easiest
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
The android dev reference should help clear things up http://developer.android.com/reference/android/os/AsyncTask.html
Related
Please help me to add update code to my app to be update from my server thank you
nothing worked from net , i need complete guide
You can't install your app without users permission and root access but you can download your applications new version from server then ask users for install. Here is an example:
{
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
version = info.versionName;
if (newversion.replace(".", "") < version.replace(".", "")) {
new DownloadFileFromURL().execute("http://exampl.com/Content/files/example.apk");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = onCreateDialog();
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
file.delete();
}
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
pDialog.setMax(lenghtOfFile / 1024);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/example.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(total / 1024 + "");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception ignored) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
//finish() or whatever you want
}
}
}
I am reading a inputstream chunck by chunk and tryng to set read chunk to a textview from a Thread class but text is only getting printed after completion of while loop below is my code :
class SendFileThread extends Thread
{
Handler mHandler;
FileInputStream instream;
SendFileThread(Handler h, FileInputStream stream )
{
mHandler = h;
instream = stream;
this.setPriority(Thread.MAX_PRIORITY);
}
#Override
public void run()
{
final StringBuilder result = new StringBuilder();
Message msg;
byte [] usbdata = new byte[64];
int readcount = 0;
sendByteCount = 0;
int val = 0;
if(instream != null)
{
try
{
readcount = instream.read(usbdata,0,64);
}
catch (IOException e){e.printStackTrace();}
while(readcount > 0)
{
sendData(readcount, usbdata);
sendByteCount += readcount;
try
{
readcount = instream.read(usbdata,0,64);
if(readcount == -1){
pending = false;
//send_file = false;
setDefaultsBoo("pending",pending, J2xxHyperTerm.this);
}else{
result.append(new String(usbdata, 0, readcount));
}
runOnUiThread(new Runnable() {
#Override
public void run() {
readText.setMovementMethod(new ScrollingMovementMethod());
readText.setText(result.toString());
//scrollView.smoothScrollTo(0, readText.getHeight() + 30);
}
});
}
catch (IOException e){e.printStackTrace();}
}
}
}
}
text is getting set to textview only after all the work is done.
After work is done, try this -
Message msg = Message.obtain(handler, what, arg1, arg2, "text");
// what= some int identififer, lets say 1101
msg.sendToTarget();
in the listening activity implement Handler.Callback. You will have to implement handleMessage
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1104: // the what identifier you set in message
String text = (String) msg.obj;
textView.setText(text)
break;
}
return false;
}
You could use an AsyncTask for this use-case, as the ability to update views on the UI thread is included right out of the box.
http://developer.android.com/reference/android/os/AsyncTask.html
This is from the usage example provided, with comments to show you where the main thread action happens.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
// Done in the background, on a separate thread
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
// This part of the loop publishes the progress to onProgressUpdate(..)
publishProgress((int) ((i / (float) count) * 100));
if (isCancelled()) break;
}
return totalSize;
}
// Called on the main thread whenever publishProgress(..) is called
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// Also called on the main thread, after the background task is finished
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Hi you can use this method in your thread :
runOnUiThread(new Runnable() {
#Override
public void run() {
//update your textview
}
});
You could use an EventBus, to communicate between your thread to your activity.
This is their github project. you can implement it and also enable communication between every Android app component. For example, like in your case, between thread and activity.
I want to update dialog's download progress from doInBackground.
I am printing log as well as publishing progress.
Neither of them are working.
It updates the dialog in the end and prints all the log values at once in the end
private class DownloadEReport extends AsyncTask<String, Void, Void> {
int progress = 0;
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(EReport.this);
mProgressDialog.setTitle("Downloads");
mProgressDialog.setMessage("Downloading, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
mProgressDialog.setProgress(progress);
}
#Override
protected Void doInBackground(String... strings) {
String mUrl = strings[0];
String json = "";
int count;
try {
URL url = new URL(mUrl);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.txt");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
// publishing the progress....
// After this onProgressUpdate will be called
Log.e("JSON Download Progress", "" + (int) ((total * 100) / lenghtOfFile));
progress = (int) (total * 100 / lenghtOfFile);
publishProgress();
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
}
}
remove super from onProgressUpdate and then try
#Override
protected void onProgressUpdate(Void... values) {
//super.onProgressUpdate(values);
mProgressDialog.setProgress(progress);
}
if it doesn't work than add a sleep statement in your loop so that this loop will free the processor and give time to publish the progress
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
One possible explanation for the behaviour is that reading from remote input stream and writing it into output buffer is extremely fast.
I tried the same code but with just a loop running for 10 times.
int total = 0;
while(total <= 100){
progress = total;
total += 10;
publishProgress();
}
Even I could not see the progress dialog at first, so put a Thread.sleep() in the loop and the progress dialog works just fine.
int total = 0;
while(total <= 100){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progress = total;
total += 10;
publishProgress();
}
Try to log the time (System.currentTimeMillis()) at which you are writing into the output buffer.
Hope it helps.
I hired someone to code my app. It loads a instrumental downloaded from the internet to my app. To download the instrumental it is fast but when loading the instrumental it takes a really long time at least a minute or more. I looked over the code to see where it would be slowing it down but i can't seem to figure it out. Any help is appreciated.
Code:
//File loading task
class SaveInputStreamTask extends AsyncTask<String, Integer, String> {
private Context context;
ProgressDialog mProgressDialog;
public SaveInputStreamTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// mProgressDialog = new ProgressDialog(context);
//mProgressDialog.setMessage("Beat Will Take A Minute To Load When Mixing So Start Recording");
mProgressDialog = ProgressDialog.show(context, getResources().getString(R.string.app_name), "Beat Will Take Up To A Minute To Load. In The Meantime How's Your Day?");
mProgressDialog.show();
}
#Override
protected String doInBackground(String... sUrl) {
try
{
File file = new File(instrument_file_name);
long totalFilesize = file.length();
long readSize = 0;
FileInputStream fis = new FileInputStream(file);
saveInputStream(fis);
return "SUCCESS";
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
if(result == null){
Toast.makeText(context, "Loading Beat failed. Please try again", Toast.LENGTH_SHORT).show();
RecordRap.this.finish();
}
else
{
}
}
public void saveInputStream(InputStream is) throws IOException
{
int n = 0;
DataInputStream in1;
in1 = new DataInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
while ((n = in1.read()) != -1)
{
bos.write(n);
}
}
catch (IOException e)
{
e.printStackTrace();
}
ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
for (int i = 0; i < sb.capacity(); i++) {
beatsShortList.add(sb.get(i));
}
}
}
So thanks to #Stephen C the problem was while ((n = in1.read()) != -1) so i added a buffer and changed the code to the following and the problem is fixed now loading only takes a few seconds. Thanks to Stephen C for the help and as Ratul Sharker.
Updated code:
byte[] buffer = new byte[0xFFFF];
while ((n = in1.read(buffer)) != -1)
{
bos.write(buffer, 0, n);
}
for (int i = 0; i < sb.capacity(); i++) {
beatsShortList.add(sb.get(i));
}
This is the culprit what are you looking for :)
I am trying to figure out the best way to loop over all ips in a range(IE 192.168.5.0-192.168.5.255) to find devices that are listening on a given port. The following code is working but I am worried that I wont find all the devices since I have my timeout on my socket too low. The catch 22 is that I want this to be super fast but if I up the timeout it starts to take forever.
private class findNetworkDevices extends AsyncTask<String, Integer, String> {
private String source;
private Activity activity;
private Context context;
public findNetworkDevices(Activity activity) {
this.activity = activity;
context = activity;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
for (int dest = 0; dest < 255; dest++) {
String host = "192.168.5." + dest; // TODO: add net address instead of hardcoding
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(InetAddress.getByName(host), 9999), 50);
Log.v(LOG_TAG, "conn:" + s.toString());
if (s.isConnected()) {
Log.v(LOG_TAG, "connected " + host);
foundDevicesArray.add(host);
} else {
return "failed";
}
} catch (Exception e) {
Log.e(LOG_TAG, "Not found", e);
}
}
Log.v(LOG_TAG, "end");
return "All Done!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListView lv = (ListView) activity.findViewById(R.id.foundDevicesList);
((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
}
}
Thanks in advance.
I went away from using Async because it took so long. I went with ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
String ip = getLocalIpAddress();
int endIndex = ip.lastIndexOf(".");
String subnet = ip.substring(0, endIndex);
for (int dest = 0; dest < 255; dest++) {
String host = subnet + "." + dest;
executor.execute(pingRunnable(host));
}
It seems to spawn multiple threads where Async did it in the background but only in one thread.