Uploading a file from android take ages before calling a function - java

I'm having a hard time with calling a function when I select on the files.
When I select on a file, it start to take like 10 seconds before it start to call the UploadFile function and then connect to the server, so when I select more files to add, it will take like a minute or so before it start to call the UploadFile function and connect to the server which is wrong. It should have start to call the UploadFile function instantly and connect to the server when I am adding more than one files.
Below is the full code:
public class ComposeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CHOOSE_FILE_REQUESTCODE = 1;
private RecyclerView mFilesDetailRecyclerView;
private ArrayList<String> mSelectedFilesList = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE) {
try {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
Context context = getApplicationContext();
FilePath = RealPathUtil.getRealPath(context, uri);
cursor.moveToFirst();
//mSelectedFilesList.add(cursor.getString(index));
mSelectedFilesList.add(FilePath);
mAdapter.notifyItemInserted(mSelectedFilesList.size());
Log.e("message.......", "caught this.....");
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
} catch (Exception e) {
Toast.makeText(ComposeActivity.this, "Choose any other file", Toast.LENGTH_SHORT).show();
}
}
}
#SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Void> {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
String twoHyphens = "--";
String boundary = "*****" + System.currentTimeMillis() + "*****";
String lineEnd = "\r\n";
Log.e("message.......", "FileName...." + FileName);
URL url = new URL("https://www.example.com/fileupload1.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(200);
urlConnection.setReadTimeout(200);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
urlConnection.setRequestProperty("uploaded_file", FileName);
FileInputStream fileInputStream = new FileInputStream(upload_File);
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file" +
"\"; filename=\"" + FileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.e("message.......", "FileName...." + FileName);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//Thread.sleep(5000);
while (bytesRead > 0) {
//int percentage = (int) ((bytesRead / (float) size) * 100);
dataOutputStream.write(buffer, 0, bufferSize);
//dataOutputStream.flush(); //doesn't help
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int code = urlConnection.getResponseCode();
StringBuilder result = new StringBuilder();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
upload_success = result.toString();
}
} catch(SocketTimeoutException e) {
//e.printStackTrace();
if (urlConnection != null) {
urlConnection.disconnect();
cancel(true);
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("message.......", "here....5");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("message.......", "here....6");
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e("message.......", "here....7");
}
catch (IOException ioException) {
ioException.printStackTrace();
Log.e("message.......", "here....2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("message.......", "here....5");
if (failtoupload == false) {
failtoupload = true;
}
if (sendMail == true) {
sendMail = false;
}
if (UpdateDraft == true) {
UpdateDraft = false;
}
if (saveDraft == true) {
saveDraft = false;
}
Date dt = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String savedDate = dateFormat.format(dt);
draftDB = new DraftDB(mContext);
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
if (attachments.equals("")) {
attachments = null;
}
}
else
{
attachments = join(", ", mSelectedFilesList);
}
if (attachments == null) {
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
}
else
{
attachments = join(", ", mSelectedFilesList);
}
}
String isImportant = "true";
String isRead = "unread";
String UpdateDB = null;
String draftID = null;
if (to == null) {
to = "";
}
if (bcc == null) {
bcc = "";
}
if (cc == null) {
cc = "";
}
if (subject == null) {
subject = "";
}
if (message == null) {
message = "";
}
if (draft_id != null) {
draftID = draft_id;
UpdateDB = "yes";
}
else
{
draftID = "";
UpdateDB = "no";
}
if (draftDB_id == 0) {
draftDB.insertDraft(from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
draftDB_id = draftDB.getID();
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.e("message.......", "here....6");
if (upload_success != null) {
if (upload_success.equals("success")) {
if (mSelectedFilesList.size() > 0) {
mSelectedFilesList.remove(0);
if (draft_id == null) {
new SaveDraft().execute();
}
else if (draft_id != null) {
if (attachment != null) {
if (mSelectedFilesList.size() >= 1) {
attid++;
for (int i = 0; i < mSelectedFilesList.size(); i++) {
String path = mSelectedFilesList.get(0);
FileName = path.substring(path.lastIndexOf("/") + 1);
attachment += " attid: " + String.valueOf(attid) + " filename: " + FileName;
}
}
}
Log.e("message........", "attachment......" + attachment);
new UpdateDrafts().execute();
}
if (mSelectedFilesList.size() >= 1) {
FilePath = mSelectedFilesList.get(0);
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
}
}
//Now time to check the upload_File
if (mSelectedFilesList.size() == 0) {
if (upload_File != null) {
upload_File = null;
}
if (FilePath != null) {
FilePath = null;
}
Log.e("message.......", "sendMail........." + sendMail);
}
if (upload_success != null) {
upload_success = null;
}
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
What I am trying to do is when I select on the file and add more files on my mobile app, I want to call the UploadFile function instantly and connect to my server to upload the file in each time when I select on the file. If the server do not response for 10 seconds and the server is offline, I want to store the data in the sqlite database.
I have been told that I should use multi thread and I should also use retrofit. I am not sure if it would be possible to use HttpUrlConnection method with multi thread to connect to the server and upload the files.
Can you please show me an example of what is the best way I could use to get instantly call to a function and connect to the server using with HttpUrlConnection if that is possible??

You start already wrong with trying to get a real path for an uri.
Remove that code.
Then instead of opening a FileInputStream open an InputStream for the uri
InputStream is = getContentResolvet().openInputStream(uri);

Related

Failed to download pdf file

I want to download this pdf file
https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf
I am using this code to download pdf files, it works fine with many files but it failed on pdf file like above
public void downloadFile(#NonNull String urlStr, #NonNull String fullFilePath,
#NonNull DownloadListener downloadListener) {
cancelStatus = false;
InputStream is = null;
File ffPath = null;
FileOutputStream fos = null;
try {
downloadListener.onProgress(0);
URL url = new URL(urlStr);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(2000000);
conexion.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5");
System.setProperty("http.agent", "");
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
if (lenghtOfFile <= 0) lenghtOfFile = 1;
is = url.openStream();
ffPath = new File(fullFilePath);
fos = new FileOutputStream(ffPath);
int count = 0;
long total = 0;
int progress = 0;
byte data[] = new byte[1024];
while ((count = is.read(data)) != -1) {
if (cancelStatus == true) {
break;
}
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress != progress_temp) {
progress = progress_temp;
downloadListener.onProgress(progress >= 0 && progress <= 100 ? progress : 0);
}
fos.write(data, 0, count);
cancelStatus = downloadListener.onPacketDownloaded(total, lenghtOfFile);
}
if (is != null) is.close();
if (fos != null) fos.close();
if (lenghtOfFile <= 1) {
downloadListener.onComplete();
} else if (ffPath.length() < lenghtOfFile) {
if (cancelStatus) {
downloadListener.onCancel();
} else {
downloadListener.onError();
}
} else if (ffPath.length() >= lenghtOfFile) {
downloadListener.onComplete();
}
if (cancelStatus == true) {
if (ffPath != null) ffPath.delete();
}
} catch (MalformedURLException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the problem is count = is.read(data) return -1 and break from while loop after one loop, the file about 345 kb
please help
/**
* download file used too download the file and save into phone
*
* #param fileURL contain file url
* #param fileName contain file name
*/
public void DownloadFile(String fileURL, String fileName) {
try {
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Cards List";
File RootFile = new File(RootDir);
RootFile.mkdir();
// File root = Environment.getExternalStorageDirectory();
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile,
fileName + " abc " + ".pdf"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Error....", e.toString());
}
} // used to download the file from server
class ProgressBack extends AsyncTask<String, Void, Void> {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
PD.setCancelable(true);
}
#Override
protected Void doInBackground(String... params) {
DownloadFile("https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf",
"Cards List"); // calling DownloadFile
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
PD.dismiss();
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}

Upload Image On Php Server In Android Programically

I am trying to upload images from android to php server The server is working all good for ios using objective c but in android I did not not know how to upload the images. I have tried the below code but the server returns message that (images are not in proper format or missing image file
ArrayList<File> imageFiles= new ArrayList<File>();
for(int i=0;i<mCameraDataList.size();i++) {
File f = new File(getFilesDir(),"image"+i+".jpg");
f.createNewFile();
Bitmap bitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeByteArray(mCameraDataList.get(i), 0, mCameraDataList.get(i).length),CommonMethods.getDeviceWidth(this), CommonMethods.getDeviceHeight(this), true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] bitmapdata = stream.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
imageFiles.add(f);
}
public static void postProduct(ArrayList<File> nImages) throws UnsupportedEncodingException {
MultipartEntityBuilder entity=MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("authenticity",new StringBody("1"));
entity.addPart("brand_id",new StringBody("1"));
entity.addPart("cat_id",new StringBody("2"));
entity.addPart("color_id1",new StringBody("2"));
entity.addPart("color_id2",new StringBody("3"));
entity.addPart("condition_id",new StringBody("3"));
entity.addPart("description",new StringBody("Bgvv"));
entity.addPart(Constants.KeyValues.DEVICE_ID,new StringBody(Constants.DEVICE_ID));
entity.addPart("images",new StringBody("images"));
entity.addPart("lon",new StringBody("74.344630"));
entity.addPart("lat",new StringBody("31.516762"));
entity.addPart("name_brand",new StringBody("2 puffs"));
entity.addPart("package_size",new StringBody("0"));
entity.addPart("selling_price", new StringBody("20"));
entity.addPart("title",new StringBody("My test"));
entity.addPart(Constants.KeyValues.UID,new StringBody(String.valueOf(CommonObjects.getUserProfile().getUid())));
for(int i=0;i<nImages.size();i++)
{
File f=new File(nImages.get(i).getAbsolutePath());
if(f.exists()){
entity.addPart(Constants.KeyValues.IMAGES, new FileBody(f, "image/jpeg"));
}
}
new SetDataToServer(Constants.NetworkServiceMethods.Product.POST_PRODUCT, entity, new SetDataToServer.SetDataNotifier() {
#Override
public void onDataReceived(boolean isError, String message, JSONObject jsonObj) {
ArrayList<String> postProductResult =new ArrayList<String>();
try {
Log.e("JSON",jsonObj.toString());
if (!jsonObj.isNull(Constants.KeyValues.DATA)) {
JSONObject jsonObjectData = jsonObj.getJSONObject(Constants.KeyValues.DATA);
// postProductResult.add(jsonObjectData.getString(Constants.KeyValues.CON_ID));
// postProductResult.add(jsonObjectData.getString(Constants.KeyValues.ORDER_ID));
}
} catch (JSONException e) {
isError = true;
message = "Sorry! Error occurred in data parsing";
}
productHandlerMethods.onPostProductResult(isError, message, postProductResult);
}
}).callServerToSetData();
}
Can any body tell what I am doing wrong.
Server side code
public function postproduct_post() {
$brand_id = $this->post('brand_id');
if ($brand_id == '') {
$brand_name = $this->post('name_brand');
if ($brand_name == '')
$this->create_error(-1);
$brand_id = $this->Mproduct->insertBrandName($brand_name);
} else {
if (!$this->Mproduct->_checkBrandId($brand_id))
$this->create_error(-15, 'brand_id');
}
$time = time();
$uid = $this->post('uid');
$cat_id = $this->post('cat_id');
$title = $this->post('title');
$description = $this->post('description');
$condition_id = $this->post('condition_id');
$authenticity = $this->post('authenticity');
$color_id1 = $this->post('color_id1', 0);
$color_id2 = $this->post('color_id2', 0);
$selling_price = $this->post('selling_price');
$package_size = $this->post('package_size');
$lat = $this->post('lat');
$lon = $this->post('lon');
if ($uid == '' || $cat_id == '' || $title == '' || $description == ''
|| $color_id1 == '' || $condition_id == '' || $authenticity == '') {
$this->create_error(-1);
}
if (!$this->Muser->_checkUid($uid))
$this->create_error(-10);
if (!$this->Mproduct->_checkCatId($cat_id))
$this->create_error(-15, 'cat_id');
if ($color_id1 > 0 && !$this->Mproduct->_checkColorId($color_id1)) {
$this->create_error(-15, 'color_id1');
}
if ($color_id2 > 0 && !$this->Mproduct->_checkColorId($color_id2)) {
$this->create_error(-15, 'color_id2');
}
$images = isset($_FILES['images']) ? $_FILES['images'] : null;
if ($images == null || count($images['name']) <= 0) {
$this->create_error(-21);
}
$this->load->model('Mfile');
if (!$this->Mfile->checkArrayImage($images)) {
$this->create_error(-13);
}
if (!$this->Mproduct->_checkConditionId($condition_id)) {
$this->create_error(-15, 'condition_id');
}
$params = array();
$params['owner_id'] = $uid;
$params['cat_id'] = $cat_id;
$params['title'] = $title;
$params['added'] = $time;
$params['brand_id'] = $brand_id;
$params['description'] = $description;
$params['is_sell'] = 1;
$params['size_id'] = 101;
$params['is_swap'] = 0;
$params['is_give'] = 0;
$params['color_id1'] = $color_id1;
$params['color_id2'] = $color_id2;
$params['condition_id'] = $condition_id;
$params['authenticity'] = $authenticity;
$params['lat'] = $lat;
$params['lon'] = $lon;
$params['last_activity'] = $time;
$params['last_comment'] = '';
$params['status'] = 1;
if ($selling_price != '')
$params['selling_price'] = $selling_price;
if ($package_size != '')
$params['package_size'] = $package_size;
$product_id = $this->Mproduct->insertProduct($params);
if ($product_id == -1) {
$this->create_error(-16);
}
$paths = $this->Mfile->saveArrayImage($images, $product_id, $time);
if (count($paths) <= 0) {
$this->create_error(-13);
}
$params = array();
$params['image'] = $this->Mfile->createThumbProduct($paths[0]);
$params['status'] = 1;
$this->Mproduct->updateAfterInsertProduct($product_id, $params);
$this->Mproduct->upItemInCat($cat_id);
$this->Mproduct->upItemInBrand($brand_id);
$this->Muser->upItemOfUser($uid);
$this->Mproduct->insertProductImage($product_id, $paths);
//$this->Mfeed->insertNotifyNewProduct($time, $uid, $product_id);
//$this->Mpush->createNotiAddProduct($uid, $product_id);
$uids = $this->Mproduct->getUidsFollowUser($uid);
$this->load->model('Mnotify');
$this->Mnotify->createNotifyMany($uids, $product_id, $uid, 7, array('product_id' => $product_id, 'uid' => $uid));
$this->Mfeed->insertFeedWhenSell($time, $product_id);
$data = array();
$data['product_id'] = $product_id;
$this->create_success($data, 'Add success');
}
Try to upload the image via below service written in android, make sure that image path is correct in below code, place the image in sdcard :
public class MyService extends Service {
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
int serverResponseCode = 0;
String upLoadServerUri = null;
private static final String TAG = "com.example.ServiceExample";
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
sharedPref = getSharedPreferences("myfiles", MODE_PRIVATE);
/************* Php script path ****************/
upLoadServerUri = "http://myserver/uploadimage.php";
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
// long endTime = System.currentTimeMillis() + 10*1000;
// while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
uploadFile(sharedPref.getString(i + "", ""));
} catch (Exception e) {
}
}
// }
Log.i(TAG, "Service running " + currentId);
}
stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
// File sourceFile = new
// File(Environment.getExternalStorageDirectory(),sourceFileUri);
File sourceFile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + fileName);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename=""+ fileName + """
// + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
return serverResponseCode;
} // End else block
}
}

App says Image Downloaded Successfully but no image shows up in gallery

The app gets the image from the given URL and displays the image and on clicking the download button, it says that the image has been downloaded successfully but there is no image in the gallery. Can someone tell me how I can fix this?
This is my Image View and Download activity. I have also added proper permissions to the Android Manifest.
private Button btnImageDownload;
private ProgressDialog pd;
private ImageView viewDownloadImage;
private Images imageId;
private File folderName;
private String imageName;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (pd != null) {
pd.dismiss();
}
Utils.showNetworkAlert(ImageViewAndDownload.this);
} else if (msg.what == 2) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image downloade succesfully",
ImageViewAndDownload.this);
// Media scaning
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else if (msg.what == 3) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image already downloaded ",
ImageViewAndDownload.this);
} else if (msg.what == 4) {
if (pd != null) {
pd.dismiss();
}
displayImageFromUrl((Bitmap) msg.obj);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
viewDownloadImage = (ImageView) findViewById(R.id.viewImage);
btnImageDownload = (Button) findViewById(R.id.btnImageDownload);
imageId = new Images();
imageName = imageId.getImageId();
LoadImageFromWeb(Constant.IMAGE_BASE_URL + File.separator + imageName);
btnImageDownload.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btnImageDownload) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Downloading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
String imageUrl = Constant.IMAGE_BASE_URL
+ File.separator + imageName;
String isDownloded = downloadImage(imageUrl, imageName);
if (isDownloded.equalsIgnoreCase("complete")) {
handler.sendEmptyMessage(2);
} else if (isDownloded.equalsIgnoreCase("")) {
handler.sendEmptyMessage(3);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(1);
}
}
}).start();
}
}
// set display image to Imageview
public void displayImageFromUrl(Bitmap obj) {
viewDownloadImage.setImageBitmap(obj);
}
// image display from the webview
private void LoadImageFromWeb(final String url1) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Loading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000
|| options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000
|| options.outHeight > 1000) {
options.inSampleSize = 2;
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(url1);
Bitmap myBitmap = BitmapFactory.decodeStream(is, null,
options);
is.close();
if (myBitmap != null) {
Message msg = new Message();
msg.obj = myBitmap;
msg.what = 4;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public InputStream getHTTPConnectionInputStream(String url1) {
URL url;
InputStream is = null;
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// image download code
public String downloadImage(String imageDownloadUrl, String imageName) {
// create directory in SDCARD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
folderName = new File(Constant.STORE_IN_FOLDER);
else
folderName = getFilesDir();
if (!folderName.exists())
folderName.mkdirs();
String response = "";
// create file name and file.
File storeImageInSDCard = new File(folderName + File.separator
+ imageName);
if (!(storeImageInSDCard.exists() && storeImageInSDCard.length() > 0)) {
// start download image
response = downloadFile(imageDownloadUrl, imageName,
folderName.toString());
}
return response;
}
// start download image
public String downloadFile(final String url, final String name,
String foldername) {
File file;
FileOutputStream os = null;
Bitmap myBitmap;
try {
URL url1 = new URL(url.replaceAll(" ", "%20"));
System.out.println("Image url :::" + url1);
HttpURLConnection urlConnection = (HttpURLConnection) url1
.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// here create a file which define folder name and image name with
// extension.
file = new File(foldername, name + ".jpg");
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
os = new FileOutputStream(file);
while ((bufferLength = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
os.flush();
os.close();
// if image size is too large we can scale image than download.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000 || options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000 || options.outHeight > 1000) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
os = new FileOutputStream(file);
myBitmap.compress(CompressFormat.JPEG, 90, os);
os.flush();
os.close();
myBitmap.recycle();
return "complete";
} catch (SQLException e) {
e.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
try this,
After saving the Image you have to use this
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
you have to send a broadcast to System ,changes to reflect in the Gallery , so that you image will be shown in the gallery , if not , you have to restart Device for check the downloaded images..
hope it helps you..
I think you have to use Aquery for image download it is very Useful for image download from net.
Here the link for Aquery

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.

download images from FTP :Caused by: java.lang.OutOfMemoryError

at com.example.newpingziyi.stir.CheckSdcard$LoadImagesFromSDCard.doInBackground(CheckSdcard.java:316)
error lines was make Stronger!
First.show that's error like java.lang.OutOfMemoryError!
this's code...
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
now i make change below code.still OutOfMemoryError yet!
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
bis.mark(0);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(bis, null, opts);
int sizes = (opts.outWidth * opts.outHeight);
if (sizes > 1024 * 1024 * 4) {
int zoomRate = 2;
if (zoomRate <= 0)
zoomRate = 1;
opts.inSampleSize = zoomRate;
}
opts.inJustDecodeBounds = false;
bis.reset();
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines!
Here is my working code for downloading Bitmap, maybe it will help :
private Bitmap downloadBitmap(String url) {
// Getting the url from the html
url = url.substring(url.indexOf("src=\"") + 5, url.length() - 1);
url = url.substring(0, url.indexOf("\""));
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}

Categories

Resources