APK file gets corrupted while writing to SD Card - java

I hit to a URL where my apk file is hosted and then write the bytes received to a file.
class DownloadAPKFile extends AsyncTask<String, Void, Boolean>{
private byte[] fileBytes;
#Override
protected Boolean doInBackground(String... params) {
Log.d("begin", "begun");
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.website/Path/my.apk");
try {
HttpResponse response = client.execute(get);
Log.d("Login", "Response " + response.getEntity());
Log.d("Login", "contentLength " + response.getEntity().getContentLength());
String responseBody = EntityUtils.toString(response.getEntity());
fileBytes = responseBody.getBytes();
Log.d("fileBytes", "fileBytes");
String filePath = Environment.getExternalStorageDirectory() + "/myappdir/" + "my" + ".apk";
File file = new File(filePath);
file.getParentFile().mkdirs();
file.createNewFile();
BufferedOutputStream objectOut = new BufferedOutputStream(new FileOutputStream(file));
Log.d("objectOut", "objectOut");
objectOut.write(fileBytes);
Log.d("write", "write");
objectOut.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This works like a charm, the problem i am having is that the content length from the entitiy is 582504 but when i look into the file manager the size goes upto 863145. I think that some data is being added while writing file to SD Card. Is there any solution to this?

This is my code which works fine, please check if this works for you
public class downloadApk extends AsyncTask<Integer, Integer, Integer>
{
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://www.tagsinfosoft.com/android/shelf/Shelf_Cam.apk");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "Shelf_Cam.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Context context=shelf.this;
pd.dismiss();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "Shelf_Cam.apk")), "application/vnd.android.package-archive");
startActivity(intent);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd=ProgressDialog.show(shelf.this,"Updating","Please wait....." );
}
}

Related

Getting bitmap as null

I am trying to download the image from url and save it in a file. But it's not getting saved. So as I debug the code I found that bitmap is always null.
code:
public class ImageUserTask extends AsyncTask<Void, Void,String> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap = null;
File directory = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); //This bitmap is null always
directory = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/Profile");
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
File mypath = new File(dir,"ProfileImage");
saveFile(mypath, bitmap);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return directory.getAbsolutePath();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
imageprofile = result;
}
}
private void saveFile(File fileName, Bitmap bmp) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
EDIT:
public class ImageUserTask extends AsyncTask<Void,Void,Bitmap> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
getImageFromUrl(strURL);
return mBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
Bitmap bitmap = result;
}
}
public Bitmap getImageFromUrl(String urlString) {
try {
URL url = new URL(urlString);
try {
if(mBitmap!=null) {
mBitmap.recycle();
mBitmap=null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
mBitmap = BitmapFactory.decodeStream(input);
convertBitmapToFile(mBitmap, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return mBitmap;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
}
What can be the reason? I have added Internet permissions too. Please help. Thank you..
class DownloadFile extends AsyncTask<String, Integer, String> {
String strFolderName;
String shareType;
String downloadPath = "";
Activity mContext;
public DownloadFile(Activity mContext) {
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
String fileName = "your filename with ext";
Log.d("TAG", fileName);
URL url = new URL("your url");
URLConnection conexion = url.openConnection();
conexion.connect();
String PATH = "your Path you want to store" + "/";
downloadPath = PATH + fileName;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(downloadPath);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String path) {
super.onPostExecute(path);
}
}
This code is work for me
Use the below methods
public Bitmap getImageFromUrl(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
try {
if(bmp!=null) {
bmp.recycle();
bmp=null;
}
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
convertBitmapToFile(bmp, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(activityRef.getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
Add android Permissions for internet and Storage
Please try this
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Cancel Async Task while downloading image

Hi,
I have an async task which downloads image via http request and shares it after completion. But if the user cancel the task, it should stop.
I'm calling it like this:
mShareImage = new shareAsync(PhotoEnlargeActivity.this).execute(imageUris.get(currentPosition));
And stopping it like this:
mShareImage.cancel(true);
But it doesn't seen to work. Async Task:
public class shareAsync extends AsyncTask<String, String, String> {
private Context mContext;
URL myFileUrl;
Bitmap bmImg = null;
Intent share;
File file;
boolean isCancelled = false;
public shareAsync(Context mContext) {
this.mContext = mContext;
}
#Override
protected void onCancelled() {
super.onCancelled();
isCancelled = true;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgressDialog("Downloading High Resolution Image for Sharing...");
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
try {
if (!isCancelled()) {
myFileUrl = new URL(args[0]);
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} else {
if (conn != null) conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Google Image Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
progressDialog.dismiss();
share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath().toString()));
mContext.startActivity(Intent.createChooser(share, "Share Image"));
}
}
Invoking the method "mShareImage.cancel(true)" will cause subsequent calls to isCancelled() to return true.
But you have to do few more things,
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically inside doInBackground.
You have added the "!isCancelled()" check beginning of the method, so it is not working.
Network operation is a blocking operation, so once its started any operation you have to wait. That's why we always do network operation in a worker thread.
Following change would solve your issue,
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
try {
myFileUrl = new URL(args[0]);
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
if (isCancelled()) return null;
conn.connect();
if (isCancelled()) return null;
InputStream is = conn.getInputStream();
if (isCancelled()) return null;
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Google Image Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
if (isCancelled()) return null;
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
progressDialog.dismiss();
share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath().toString()));
if (isCancelled()) return;
mContext.startActivity(Intent.createChooser(share, "Share Image"));
}

Download a large pdf with jsoup

I would like to download a large pdf file with jsoup. I have try to change timeout and maxBodySize but the largest file I could download was about 11MB. I think if there is any way to do something like buffering. Below is my code.
public class Download extends Activity {
static public String nextPage;
static public Response file;
static public Connection.Response res;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle b = new Bundle();
b = getIntent().getExtras();
nextPage = b.getString("key");
new Login().execute();
finish();
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
res = Jsoup.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.execute();
SharedPreferences pref = getSharedPreferences(
MainActivity.PREFS_NAME, MODE_PRIVATE);
String username1 = pref.getString(MainActivity.PREF_USERNAME,
null);
String password1 = pref.getString(MainActivity.PREF_PASSWORD,
null);
file = (Response) Jsoup
.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.maxBodySize(1024*1024*10*2)
.timeout(70000*10)
.cookies(res.cookies()).data("uname", username1)
.data("pass", password1).data("next", nextPage)
.data("submit", "").method(Method.POST).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
String name = "eclassTest.pdf";
FileOutputStream out;
try {
int len = file.bodyAsBytes().length;
out = new FileOutputStream(new File(PATH + name));
out.write(file.bodyAsBytes(),0,len);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I hope somebody could help me!
I think, it's better to download any binary file via HTTPConnection:
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://example.com/file.pdf");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
Jsoup is for parsing and loading HTML pages, not binary files.

Discover Filename and Extension from a Download Link [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to download a file using a download_url but actually it's not the download link
When I hit the download_url Actual file download starts which actually contains filename and extension
Now I want to discover filename and extension
I've tried this
FilenameUtils.getExtension(download_url);
FilenameUtils.getName(download_url)
And also this
URLUtil.guessFileName(download_url, null, null);
But I'm getting an empty string, how to find filename and extension?
Check the codes in the below that download PDF File and Open Directly in PDF Viewer:
downloadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String URL = "www.XXXXX.com";
if (NetworkUtil.isConnectingToInternet(getActivity())) {
downloadPDFAsyncTask pdfAsyncTask = new downloadPDFAsyncTask();
pdfAsyncTask.execute();
} else {
NetworkUtil.showDialog(getActivity(),
R.string.internetTitle,
R.string.internetMessage);
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private class downloadPDFAsyncTask extends
AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
NetworkUtil.showProgressDialog(getActivity());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... aurl) {
try {
System.out.println("URL >>>>> " + URL);
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
// connect
urlConnection.connect();
checkAndCreateDirectory("/fileDirectory");
file = new File(rootDir, "fileDirectory");
System.out.println("file >>>>> " + file);
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
System.out.println("totalSize >>>>> " + totalSize);
// create a buffer...
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
// close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
try {
NetworkUtil.hideProgressDialog(getActivity());
PackageManager packageManager = getActivity()
.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List<?> list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0 && file.isFile()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} else {
NetworkUtil
.showDialog2(getActivity(), "Error",
"PDF Reader application is not installed in your device");
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// function to verify if directory exists
public void checkAndCreateDirectory(String dirName) {
File new_dir = new File(rootDir + dirName);
if (!new_dir.exists()) {
new_dir.mkdirs();
}
}

how to get binary format values from video file? [duplicate]

I want to upload a video in web server. I got the service which to i want to pass a file in binary format how can i do this ?
I have tried to convert the video file into binary format with the help of base64..?
public class binaryformat extends Activity {
private String strAttachmentCoded;
Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
File file = new File("/mnt/sdcard/C:/Program Files (x86)/Wowza Media Systems/Wowza Media Server 3.1.2/content/sample.mp4");
FileInputStream objFileIS = null;
try
{
objFileIS = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
byte[] byteBufferString = new byte[1024];
try
{
for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1;)
{
objByteArrayOS.write(byteBufferString, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] byteBinaryData = Base64.encode((objByteArrayOS.toByteArray()), Base64.DEFAULT);
strAttachmentCoded = new String(byteBinaryData);
}
});
}
}
I have experienced in my 3 application that it is good if use XML to send the IMAGE or VIDEO over server.
Sending IMAGE or VIDEO in the form of base64 String in the XML is best if you want to upload a IMAGE or VIDEO in ANDROID.
public static String uploadMultiplePhoto(String url, String xmlString) {
String responseString = "";
try {
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost request = new HttpPost(url);
//convert parameters into JSON object
//JSONObject holder = new JSONObject(jsonObjString);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(xmlString);
//sets the post request as the resulting string
request.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
request.setHeader("Accept", "application/xml");
/*request.setHeader("Content-type", "application/xml");*/
//Handles what is returned from the page
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseString = httpclient.execute(request, responseHandler);
} catch (Exception exception) {
exception.printStackTrace();
}
return responseString;
}

Categories

Resources