This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Downloading multiple files one by one using AsyncTask?
I am trying to download images (probably about 20?) and then saving them into cache.
How do I implement a download progress bar? Each image is from a individual link, if i implement a download progress bar.. would it load the download bar twenty times in my case?
this is the way i download the image and save them as cache:
/**
* Background Async Task to Load all product by making HTTP Request
* */
class downloadMagazine extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading.." + "\n" + "加载中..");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
/**
* getting preview url and then load them
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_magazine, "GET", params);
// Check your log cat for JSON reponse
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// magazines found
// Getting array of magazines
mag = json.getJSONArray(TAG_MAGAZINE);
for (int i = 0; i < mag.length(); i++) {
JSONObject c = mag.getJSONObject(i);
// Storing each json item in variable
String magazineUrl = c.getString(TAG_MAGAZINE_URL);
//String issueName = c.getString(TAG_MAGAZINE_NAME);
urlList.add(magazineUrl);
//issueNameList.add(issueName);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// Building Parameters
List<NameValuePair> param = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json1 = jParser.makeHttpRequest(urlList.get(pos), "GET", param);
// CHECKING OF JSON RESPONSE
// Log.d("All guide: ", json.toString());
try {
issues = json1.getJSONArray(TAG_ISSUE);
for (int i = 0; i < issues.length(); i++) {
JSONObject c = issues.getJSONObject(i);
String image = c.getString(TAG_IMAGE);
imageList.add(image);
//System.out.println(imageList);
}
// STOP THE LOOP
//break;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
/**
* Updating parsed JSON data into ListView
* */
progressDialog.dismiss();
getBitmap();
buttonsCheck();
}
}
private Bitmap getBitmap() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory() + folderName+"/Issues/"+issueNumber);
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
for (int i=0; i<=imageList.size()-1; i++)
{
String image= imageList.get(i);
try
{
String filename = String.valueOf(image.hashCode());
Log.v("TAG FILE :", filename);
File f = new File(cacheDir, filename);
// Is the bitmap in our cache?
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
// Download it
try {
bitmap = BitmapFactory.decodeStream(new URL(image)
.openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
Log.v("FILE NOT FOUND", "FILE NOT FOUND");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
private void writeFile(Bitmap bmp, File f) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (Exception ex) {
}
}
}
PS: the progress bar I meant was those that shows the % to completion
count the total size of all images,
show progressbar and start downloading your files,
while downloading update your progress,
only after all files are downloaded remove your bar.
Related
I have parsed JSON successfully but now i want to Cache it for offline usage, even internet is not available, and if any new entry comes i want to cache that as well.
And what would be the best option to cache data ? SharedPreferences or SQLite database
Here is my code, which i am using to Parse JSON:
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
Why not just save it to cache folder of your app using something like this:
String path = Environment.getExternalStorageDirectory() + File.separator + "cache" + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
path += "data";
File data = new File(path);
if (!data.createNewFile()) {
data.delete();
data.createNewFile();
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
objectOutputStream.writeObject(actorsList);
objectOutputStream.close();
And after, you can read it in any time using:
List<?> list = null;
File data = new File(path);
try {
if(data.exists()) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
list = (List<Object>) objectInputStream.readObject();
objectInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
UPDATE: Okay, make class named ObjectToFileUtil, paste this code to created class
package <yourpackagehere>;
import android.os.Environment;
import java.io.*;
public class ObjectToFileUtil {
public static String objectToFile(Object object) throws IOException {
String path = Environment.getExternalStorageDirectory() + File.separator + "cache" + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
path += "data";
File data = new File(path);
if (!data.createNewFile()) {
data.delete();
data.createNewFile();
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
objectOutputStream.writeObject(object);
objectOutputStream.close();
return path;
}
public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
Object object = null;
File data = new File(path);
if(data.exists()) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
object = objectInputStream.readObject();
objectInputStream.close();
}
return object;
}
}
Change < yourpackagehere > to your package name and don't forget to add WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml. In your MainActivity add field
private String dataPath;
and replace your onPostExecute method of JSONAsyncTask class to
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result) {
try {
dataPath = objectToFile(arrayList);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
Now you can access get actorsList from File anytime when you want, by using
try {
actorsList = (ArrayList<Actors>)objectFromFile(dataPath);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
If you want to save path of file after closing application you must save dataPath string (and load on application start), for example, using SharedPreferences.
And what would be the best option to cache data ? SharedPreferences or SQLite database
Which is purely based on the data you received.
If the data is Small,Unstructured data then use Shared Pref.
If the data is Large,Structured data then use SQLite.
But for store the full data better you can use file concept. Store the string data in your code String data = EntityUtils.toString(entity); the data you have to save to the file.If any changes in the data from the server add that to file.And retrieve the data if internet not present. Get the example code for file operations from the above link.
In my program i am downloading a Json array file contating data of notices. Each notice contain an address field from where senders image is to be downloaded. So I run another async task to download the images for each json array object. But only 1st image is downloaded no matter how many element json array has. I even tried executeOnExecutor but only folders were created and no images were downloaded.
The onpostexecute method is as below
#Override
protected void onPostExecute(JSONObject jsonObject) {
// TODO Auto-generated method stub
super.onPostExecute(jsonObject);
try {
if (jsonObject.getString("status").equalsIgnoreCase("true")) {
// refining the notices sent by server
JSONArray jsonArray = jsonObject.optJSONArray("notices");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonArrayChild = jsonArray.getJSONObject(i);
// Retrieving data for each notice item
String name = jsonArrayChild.optString("name");
String heading = jsonArrayChild.optString("heading");
String date = jsonArrayChild.optString("date");
String noticeContent = jsonArrayChild
.optString("content");
imageaddress = jsonArrayChild.optString("image");
imageName = imageaddress.substring(
imageaddress.lastIndexOf("/") + 1,
imageaddress.length());
// first we need to download the image from location
// specified in string imageaddress
new ProcessDownloadNoticeSenderImage()
.execute(imageaddress);
// now inserting the overall data into database
// storing the local address of downloaded image in
// database
File file = new File(
Environment.getExternalStorageDirectory()
+ "/veda/images/" + imageName);
String localImageAddress = file.getAbsolutePath();
// storing data in database
noticeMainDatabase.insertNotice(name, heading, date,
noticeContent, localImageAddress);
// first we need to download the image from location
// specified in string imageaddress
}
}
}
and ProcessDownloadNoticeSenderImage is as below
private class ProcessDownloadNoticeSenderImage extends
AsyncTask<String, Integer, Bitmap> {
Bitmap bitmap = null;
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
File folder = new File(Environment.getExternalStorageDirectory()
+ "/veda/images");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(
getApplicationContext(),
"veda/images folder is successfully created to store the images",
Toast.LENGTH_SHORT).show();
}
// saving the downloaded image into folder
File f = new File(Environment.getExternalStorageDirectory(),
"/veda/images/" + imageName);
if (f.exists()) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
} else if (!f.exists()) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
}
try {
bitmap = downloadImageFromServer(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
help me in how to download multiple images so that i can show them in list.
I have several files uploaded to my server , now what i am trying to do is i want to download all files one by one and save it in to one folder.
So basically i was trying to do something like [this][1] but some how i am not able to achieve this so i think an alternate way to do it. So i am planning to download all audio file of particular folder of server to my SD-card folder and then i will give path of SD-card to list-view and play that audio.
So basically my question is how can i download all file from server folder to my SD-card folder.
I have below piece of code which is working fine for single file.
public class ServerFileList extends Activity {
Uri uri;
URL urlAudio;
ListView mListView;
ProgressDialog pDialog;
private MediaPlayer mp = new MediaPlayer();
private List<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.serverfilelist);
mListView = (ListView) findViewById(R.id.listAudio);
// new getAudiofromServer().execute();
new downloadAudio().execute();
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(urlAudio + myList.get(position));
}
});
}
public void updateProgress(int currentSize, int totalSize) {
TextView mTextView = new TextView(ServerFileList.this);
mTextView.setText(Long.toString((currentSize / totalSize) * 100) + "%");
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
class downloadAudio extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ServerFileList.this);
pDialog.setMessage("Downloading File list from server, Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// set the download URL, a url that points to a file on the internet
// this is the file to be downloaded
URL url = null;
try {
url = new URL("http://server/folder/uploadAudio/abcd.mp3");
} catch (MalformedURLException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// create the new connection
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e5) {
// TODO Auto-generated catch block
e5.printStackTrace();
}
// set up some things on the connection
try {
urlConnection.setRequestMethod("GET");
} catch (ProtocolException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
urlConnection.setDoOutput(true);
// and connect!
try {
urlConnection.connect();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// set the path where we want to save the file
// in this case, going to save it on the root directory of the
// sd card.
String MEDIA_PATH = new String(
Environment.getExternalStorageDirectory()
+ "/newDirectory/");
File SDCardRoot = new File(MEDIA_PATH);
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
// create a new file, specifying the path, and the filename
// which we want to save the file as.
File file = new File(SDCardRoot, System.currentTimeMillis()
+ ".mp3");
// this will be used to write the downloaded data into the file we
// created
FileOutputStream fileOutput = null;
try {
fileOutput = new FileOutputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// this will be used in reading the data from the internet
InputStream inputStream = null;
try {
inputStream = urlConnection.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// this is the total size of the file
int totalSize = urlConnection.getContentLength();
// variable to store total downloaded bytes
int downloadedSize = 0;
// create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; // used to store a temporary size of the
// buffer
// now, read through the input buffer and write the contents to the
// file
try {
while ((bufferLength = inputStream.read(buffer)) > 0) {
// add the data in the buffer to the file in the file output
// stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
// add up the size so we know how much is downloaded
downloadedSize += bufferLength;
// this is where you would do something to report the
// prgress,
// like this maybe
updateProgress(downloadedSize, totalSize);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close the output stream when done
try {
fileOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
// catch some possible errors...
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
class getAudiofromServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ServerFileList.this);
pDialog.setMessage("Getting File list from server, Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... arg0) {
try {
urlAudio = new URL("http://server/folder/uploadAudio");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ApacheURLLister lister1 = new ApacheURLLister();
try {
myList = lister1.listAll(urlAudio);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ServerFileList.this, android.R.layout.simple_list_item_1,
myList);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setCacheColorHint(Color.TRANSPARENT);
}
}
}
Try follow steps,
Write a server side component which will return back the list of the files in the directory in which all the audio files are hosted.
In your downloadAudio class, instead of downloading a file, initially make a call to the component described above to get the list.
Move the code which you have written in an function which will take String argument.
Loop on the url list from step 2 and call function in step 3 with parameter as current element of url list.
Keep all checks and balances to ensure all the files are downloaded.
Your issue is more of design issue then programming.
I have solved the problem by adding ivy jar file as a library and then added following code.
try {
urlAudio = new URL("http://server/folder/uploadAudio");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ApacheURLLister lister1 = new ApacheURLLister();
try {
myList = lister1.listAll(urlAudio);
} catch (IOException e) {
e.printStackTrace();
}
return null;
I have the following piece of code and I would want to add a feature in here such that I know when the JSON content is uploaded. I am uploading a JSON content.
#Override
protected String doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
String state = "";
HttpPost httpPost = new HttpPost(commentURL);
StringEntity se = null;
HttpResponse response = null;
HttpEntity entity = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
InputStream is = null;
try {
se = new StringEntity(params[0].toString());
Log.i("SE", params[0].toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
try {
response = httpClient.execute(httpPost);
Log.i("HTTP POST", httpPost.toString());
Log.i("RESPONSE", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
state = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return state;
}
I tried researching myself, which is where I stumbled upon the MultipartEntity, but since I am to upload a simple JSON content through POST I didn't find this necessary to use. So how do I show how much progress is made in the upload process and also what is the total size of the JSON content ?? I sort of figured that I would have had to use the StringEntity ? Am I right ?
Initiate your progress bar as
private ProgressDialog pDialog;
On onPreExecute()
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
On onPostExecute()
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
}
For showing progress bar with percentage try ..
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "your_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
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.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
I am developing an app for upload video to a Apache/PHP Server. In this moment I already can upload videos. I need show a progress bar while the file is being uploaded. I have the next code using AsyncTask and HTTP 4.1.1 Libraries for emulate the FORM.
class uploadVideo extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");
try {
// Add your data
File input=new File(fileName);
MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multi.addPart("video", new FileBody(input));
httppost.setEntity(multi);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(
new InputStreamReader(
entity.getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (ClientProtocolException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
}
return "error";
}
#Override
protected void onProgressUpdate(Void... unsued) {
//Here I do should update the progress bar
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (pd.isShowing())
pd.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Video uploaded successfully",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
I need know where I can get how much bytes has been uploaded. File.length is the total size.
Have you tried extending FileBody? Presumably the POST will either call getInputStream() or writeTo() in order to actually send the file data to the server. You could extend either of these (including the InputStream returned by getInputStream()) and keep track of how much data has been sent.
thank to cyngus's idea I have resolved this issue. I have added the next code for tracking the uploaded bytes:
Listener on upload button:
btnSubir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//pd = ProgressDialog.show(VideoAndroidActivity.this, "", "Subiendo Video", true, false);
pd = new ProgressDialog(VideoAndroidActivity.this);
pd.setMessage("Uploading Video");
pd.setIndeterminate(false);
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
//Thread thread=new Thread(new threadUploadVideo());
//thread.start();
new UploadVideo().execute();
}
});
Asynctask for run the upload:
class UploadVideo extends AsyncTask<Void,Integer,String> {
private FileBody fb;
#Override
protected String doInBackground(Void... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");
int count;
try {
// Add your data
File input=new File(fileName);
// I created a Filebody Object
fb=new FileBody(input);
MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multi.addPart("video",fb);
httppost.setEntity(multi);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//get the InputStream
InputStream is=fb.getInputStream();
//create a buffer
byte data[] = new byte[1024];//1024
//this var updates the progress bar
long total=0;
while((count=is.read(data))!=-1){
total+=count;
publishProgress((int)(total*100/input.length()));
}
is.close();
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(
new InputStreamReader(
entity.getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (ClientProtocolException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.v("Uri Galeria", e.toString());
e.printStackTrace();
}
return "error";
}
#Override
protected void onProgressUpdate(Integer... unsued) {
pd.setProgress(unsued[0]);
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (pd.isShowing())
pd.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),sResponse,Toast.LENGTH_SHORT).show();
Log.i("Splash", sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
The progress bar load is bit slow (in starting seems be freeze and then load of 1 to 100 very fast), but works.
Sorry, my english is regular :(.
Check my answer here, I guess it answers your question:
But update the file path of the image to your to be uploaded video
https://stackoverflow.com/questions/15572747/progressbar-in-asynctask-is-not-showing-on-upload
What I used to do is to extends org.apache.http.entity.ByteArrayEntity and override the writeTo function like below, while bytes output it will pass though writeTo(), so you can count current output bytes:
#Override
public void writeTo(final OutputStream outstream) throws IOException
{
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new ByteArrayInputStream(this.content);
try {
byte[] tmp = new byte[512];
int total = (int) this.content.length;
int progress = 0;
int increment = 0;
int l;
int percent;
// read file and write to http output stream
while ((l = instream.read(tmp)) != -1) {
// check progress
progress = progress + l;
percent = Math.round(((float) progress / (float) total) * 100);
// if percent exceeds increment update status notification
// and adjust increment
if (percent > increment) {
increment += 10;
// update percentage here !!
}
// write to output stream
outstream.write(tmp, 0, l);
}
// flush output stream
outstream.flush();
} finally {
// close input stream
instream.close();
}
}