How to Cache Parsed JSON for Offline usage - android

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.

Related

How to parse json from asset folder to listview?

I want to parse text and image from a json on file in asset folder to my listview. Please explain clearly because I am biginner in android. Give me complete codes of all files. Thank you a lot.
Just open the file from the assets folder like this
StringBuilder buf=new StringBuilder();
InputStream json;
try {
json = context.getAssets().open("YOUR_FILE_NAME.txt");
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;
while ((str=in.readLine()) != null) {
buf.append(str);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
result1 = buf.toString();
result1 will have the complete json from your file
then use this library called Gson to parse the json ...
Here is the tutorial for it Json parsing through Gson
Maybe code can help you.
public class MainActivity extends Activity {
private ListView listView;
private void log(String msg) {
Log.d("DNB", this.getClass().getName() + ">>" + msg);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.listView = new ListView(this);
String jsonData = loadJsonFromAsset();
String[] items = parseJson(jsonData);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
setContentView(listView);
log("json from asset: " + jsonData);
}
private String[] parseJson(String jsonData) {
String[] items = new String[0];
if (jsonData != null) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
if (jsonArray != null) {
items = new String[jsonArray.length()];
for (int i = 0; i < items.length; i++) {
items[i] = jsonArray.get(i).toString();
}
}
} catch (JSONException e) {
log("err--" + e.toString());
}
}
return items;
}
private String loadJsonFromAsset() {
InputStream stream;
try {
stream = getBaseContext().getAssets().open("json_list.txt");
if (stream != null) {
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
if (buffer != null) {
return new String(buffer);
}
}
} catch (IOException e1) {
log("err--" + e1.toString());
}
return "";
}
And json file at assets
["item line 1","item line 2","item line 3"]

Not able to downloade multiple images at same time

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.

Write /Read String Array to File in Android, using internal or external storage whichever is available

I am downloading a json response array string from network and displaying a listview using this data.I want to store this response for first time in a file stored under internal/external storage, so i dont have to download the data again in future.
How can i store this response in a internal/external storage file and read it later when my application starts afresh again.And File should be created first time only and later when application is started again, a check to whether file exists or not should be in place.
Any examples /utility class where this has been done?
Here is my code...
The Problem with this code is...it always creates a new directory and a new file.
public class FileCache {
static File cacheDir;
static final String DIRECTORY_ADDRESS = "/Android/data/com.example.savefiletostoragedemo/.newDirectory";
static final String TAG="DEMO";
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
cacheDir = new File(Environment.getExternalStorageDirectory(),DIRECTORY_ADDRESS);
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.exists());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.exists());
}
if(!cacheDir.exists()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
public static void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
I call createDirectory() in Application class
MainActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadUrsl().execute(null,null,null);
}
private class DownloadUrsl extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
File f = getJson("LISTVIEWDATA");
//String jsonString =FileCache.readFromFile(f);
//Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]")
return null;
}
private File getJson(String filename) {
File f = FileCache.getFile(filename);
if(f != null && f.isFile()) {
String jsonString =FileCache.readFromFile(f);
Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]");
return f;
}
try {
Log.i("DEMO", "Starting data download...");
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
URI uri = new URI("");
HttpResponse httpResponse = httpclient.execute(new HttpGet(uri));
String response =EntityUtils.toString(httpResponse.getEntity());
Log.i("DEMO", "DATA Received from net is:[ "+response+" ]");
JSONArray array=new JSONArray(response);
FileCache.saveFile(array.toString(), f);
return f;
} catch (Exception ex) {
return null;
}
}
}
Issues with this Code: This code always creates a new directory when application starts...And also creates a new file everytime the data is requested.I also tried isDirectory(), didnt work.
here is how i did it.. Thank you guys For Your Help..:)
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
cacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.isDirectory());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.isDirectory());
}
if(!cacheDir.isDirectory()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, String.valueOf(filename.hashCode()));
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
private static final String cacheDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + MyUtilClass.class.getPackage().getName();
public static void cacheResponse(String name, List<String> data) throws IOException {
File f = new File(cacheDir + "/" + name);
if (f.exists())
return;
Writer fw = new FileWriter(f);
for (String line : data) {
fw.write(line);
}
fw.close();
}

how to create a string representation of json

hey there guys and girls i have this code that saves json as a string representation, i still haveing a little trouble understanding how the entity section works, and need to know how to change my code so that it works, this is the error im getting,
Error saving string java.lang.NumberFormatException: unable to parse '[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]' as integer
i was getting help from someone last night that almost got me there but still need a little more understanding of how it works and wht i get the parse error here is my full code
public class MainActivity extends Activity {
String entityString = null;
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
Integer responseInteger = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button that saves the file from mySQL
Button save = (Button) findViewById(R.id.downloadBtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveJson();
}
});
//Button that opens the file from InternalMemory
Button open = (Button) findViewById(R.id.showBtn);
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJson();
}
});
//end of onCreate()
}
//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
//connects to mySQL
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
HttpResponse response = client.execute(post);
//captures the response
entity = response.getEntity();
InputStream entityStream = entity.getContent();
StringBuilder entityStringBuilder = new StringBuilder();
byte [] buffer = new byte[1024];
int bytesReadCount;
while ((bytesReadCount = entityStream.read(buffer)) > 0) {
entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
}
entityString = entityStringBuilder.toString();
responseInteger = Integer.valueOf(entityString);
}catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
//is = entity.getContent();
String FILENAME = "story.json";
//gives file name
FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
//creates new StreamWriter
OutputStreamWriter writer = new OutputStreamWriter(output);
//writes json with file name story.json
writer.write(entityString);
writer.flush();
//closes writer
writer.close();
}catch(Exception e) {
Log.e("log_tag", "Error saving string "+e.toString());
}
//end of saveJson()
}
public void openJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
FileInputStream fileInput = openFileInput("story.json");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = inputReader.readLine()) != null) {
strBuilder.append(line + "\n");
}
fileInput.close();
storyObj = strBuilder.toString();
}catch(IOException e){
Log.e("log_tag", "Error building string "+e.toString());
}
try{
JSONArray jArray = new JSONArray(storyObj);
String storyNames = "";
for(int i = 0;i<jArray.length();i++){
storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
}
test.setText(storyNames);
}catch(JSONException e) {
Log.e("log_tag", "Error returning string "+e.toString());
}
return;
//and of openJson()
}
//end of class body
}
My guess it your code failed at this lines:
responseInteger = Integer.valueOf(entityString);
After a little inspection, I see that your JSON is:
[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]
A closer inspection using JSON Viewer, I see that your structure is like this:
The problem is
I don't see any integer in this JSON. You might have to use a combination of JSONObject and JSONArray to parse your it properly.
Your problem is this line
responseInteger = Integer.valueOf(entityString);
entityString is
'[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]'
And when Integer.valueOf tries to parse it, it can't parse it as an integer, so it throws a NumberFormatException.
Sample JSon string:
{
Stories:
[
{
"story_name": "Story One"
},
{
"story_name": "Story Two"
}
]
}
Create a Class:
public class Story
{
public String stort_name;
}
class CollectionOfStories
{
public List<Story> Stories;
public CollectionOfSections()
{
Stories= new ArrayList<Story>();
}
}
Finally:
private CollectionOfStories convertDataFromJSonToObject(String jsonString)
{
JSONObject jso;
CollectionOfStories colStories = new CollectionOfStories();
try
{
jso = new JSONObject(jsonString);
JSONArray ja = jso.getJSONArray("Stories");
for (int i = 0; i < ja.length(); i++)
{
Story s = new Story();
JSONObject jsonSection = ja.getJSONObject(i);
s.stort_name = jsonSection.getString("story_name");
//add it to sections list
colStories.Stories.add(s);
}
}
catch (NumberFormatException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return colStories;
}

I need know how much bytes has been uploaded for update a progress bar android

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();
}
}

Categories

Resources