Downloading a pdf file of larger size(like 30Mb) fails - codenameone

I have used CN1CircleProgress library while downloading pdf files. It works great if the pdf file is small. But for larger pdf files eg 30 Mb, the circle fills to 100% 2-3 times very quickly and then again it starts to download to 20-30% & download stops. The file downloaded is currupted & cannot be opened in pdf viewer. I have checked it in iOS & android devices. In simulator it just downloads to certain percent, then it stops
downloadPdfButton.addActionListener((e) -> {
pdfUrlSelected = "http://roundtablenepal.org.np/uploadEpubs/57cbcc4e76258.pdf";
pdfFileNameIdSelected = currentPdfSelected.get("magazine_title");
filename = dir + sep;
filename = filename + pdfFileNameIdSelected + ".pdf";
FileSystemStorage.getInstance().mkdir(dir);
Slider downloadSlider = new Slider();
if (!FileSystemStorage.getInstance().exists(filename)) {
downloadPdfFromUrl(f, pdfUrlSelected, filename, true, downloadSlider, findCancelDownload(f));
}
});
private boolean downloadPdfFromUrl(Form f, String url, final String fileName, boolean storage, final Slider slider, Button cancel) {
crPdf = new ConnectionRequest();
crPdf.resume();
crPdf.setPost(false);
crPdf.setDuplicateSupported(true);
crPdf.setFailSilently(true);
crPdf.setUrl(url);
crPdf.setTimeout(15000);
crPdf.setDestinationFile(fileName);
final CircleFilledProgress p = new CircleFilledProgress();
p.setProgress(0);
f.add(BorderLayout.CENTER, p);
NetworkManager.getInstance().addProgressListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (evt instanceof NetworkEvent) {
NetworkEvent e = (NetworkEvent) evt;
if (e.getProgressPercentage() >= 0) {
slider.setText(e.getProgressPercentage() + "%");
slider.setProgress(e.getProgressPercentage());
}
}
}
});
slider.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
p.setProgress(index);
}
});
NetworkManager.getInstance().addToQueueAndWait(crPdf);
cancel.addActionListener((e) -> {
crPdf.kill();
});
return crPdf.getResponseCode() == 200;
}

I suggest opening the network monitor, I'm guessing you are getting a redirect which updates the progress then the redirect leads to an error page for some reason.

Related

How to open a PDF file downloaded and stored in the Download folder an a mobile device?

I've researched different solutions to this problem, but none of them works for me. I am trying to download a file from Firebase (which I am successful in doing) and then I am trying to open that file in my app right after the download completes. However, my app either crashes or does nothing.
Below is the code for downloading the file (from FirebaseStorage which works):
public void download(String name) {
final String pdf_name = name.substring(0, name.lastIndexOf('.'));
storageReference = firebaseStorage.getInstance().getReference();
ref=storageReference.child("Auctions/" + name);
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFile(ActiveAuctionsActivity.this, pdf_name, ".pdf", DIRECTORY_DOWNLOADS, url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
SpannableString spannableString = new SpannableString("אין תיק עבודה למכרז זה");
spannableString.setSpan(
new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light)),
0,
spannableString.length(),
0);
Toast.makeText(ActiveAuctionsActivity.this, spannableString, Toast.LENGTH_LONG).show();
}
});
}
public void downloadFile(Context context, String fileName, String fileExtention, String destinationDirectory, String url){
DownloadManager downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDescription("מוריד.....");
//request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtention);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName + fileExtention);
// call allowScanningByMediaScanner() to allow media scanner to discover your file
request.allowScanningByMediaScanner();
downloadmanager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Toast.makeText(getApplicationContext(), "מוריד את התיק העבודה.....",
Toast.LENGTH_SHORT).show();
}
After, I setup the receiver with the openFile() method:
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(getApplicationContext(), "ההורדה הסתיימה",
Toast.LENGTH_LONG).show();
openFile("GMU.pdf");
}
};
public void openFile(String fileName){
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri path = Uri.fromFile(file);
Log.i("Fragment2", String.valueOf(path));
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ActiveAuctionsActivity.this, "error", Toast.LENGTH_LONG).show();
}
}
Again, the file does download, but doesn't open.
What am I doing wrong, could you please advise me?
EDIT
I also tried the code below as my openFile() but that also doesn't work:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setDataAndType(path, pdfOpenintent.getType());
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
ActiveAuctionsActivity.this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
pdfOpenintent.setType("application/*");
startActivity(Intent.createChooser(pdfOpenintent, "No Application found to open File - " + fileName));
}

Android: MediaRecorder stop() freezes app

I have an app to record screen videos. On some devices e.g. OnePlus 3t it works fine but on other devices like Samsung Galaxy s9 it freezes the whole app after stopping recording.
This is how I initialize the recorder:
private void initRecorder() {
mediaRecorder = new MediaRecorder();
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss")
.format(new Date());
File storeDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Videos");
if (!storeDirectory.exists()) {
boolean success = storeDirectory.mkdirs();
if (!success) {
Log.e(TAG, "failed to create file storage directory.");
return;
}
}
mediaRecorder.setOutputFile(storeDirectory + "/video" + timeStamp + ".mp4");
mediaRecorder.setVideoSize(screenWidth, screenHeight);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoFrameRate(16);
mediaRecorder.setVideoEncodingBitRate(3000000);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mediaRecorder.setOrientationHint(orientation);
mediaRecorder.prepare();
}
The start method is invoked on a button click. When this button is clicked again it stops recording an the following method is called. This it where it freezes everything.
private void stopRecording() {
if (virtualDisplay == null) {
return;
}
virtualDisplay.release();
mediaRecorder.stop(); --> freeze
isRecording = false;
}
I have also tried to call the method stopRecording() in a separate thread. Then it does not freeze but the video is not saved. It seems to do heavy stuff in the stop() method that will never end. Any ideas?

Temp png file from storage not uploading

Okay, I don't believe this is a cn1 issue, but I am running out of options. I have an app and I have been using the Capture.capturePhoto to give the user the ability to snap a photo with their device and upload it to my server. Has been working great for several months now. I have been asked to add the ability to upload a photo from the mobiles photo gallery, I thought it would be trivial, but after figuring out how to scale the image down and store it in Storage, I am now stumped with it just sending 0 bytes to my server.
I know it's not my server, that has not changed and can still upload files from various sources including the ones captured with the photo in the cn1 app.
Here is the code that uploads the photo
private void uploadImage(String filename, String name) throws IOException {
String ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("pjpeg") || ext.equals("png")) {
MultipartRequest request = new MultipartRequest() {
Hashtable h;
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
h = p.parse(new InputStreamReader(input));
super.readResponse(input);
}
#Override
protected void postResponse() {
List<Map<String, Object>> media = (List<Map<String, Object>>)h.get("media");
Dialog.show("Photo Uploaded", media.size() + " photo(s) uploaded and available to send.", "OK", null);
}
};
request.setUrl(MyApplication.IMGSERVER);
request.setPost(true);
request.addData(name, filename, "image/" + ext);
request.addRequestHeader("X-Dart-Token", token);
NetworkManager.getInstance().addToQueue(request);
} else {
Dialog.show("Invalid Photo Format", "The photo format (" + ext+ ") is not supported. Try with jpg or png.", "OK", null);
}
}
Here is the relevant parts of code that get and scale the photo from the gallery
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent != null && actionEvent.getSource() != null) {
String filepath = (String)actionEvent.getSource();
if (filepath != null) {
// scale down the image
String filename = "tempfile.png";
boolean success = false;
if (Storage.isInitialized()) {
try {
OutputStream out = Storage.getInstance().createOutputStream(filename);
ImageIO.getImageIO().save(filepath, out, ImageIO.FORMAT_PNG, 500, -1, 1);
out.close();
success = true;
} catch (IOException e1) {
Log.p("image scaling failed " + e1.getMessage());
Dialog.show("Photo Upload", "Unable to scale photo:" + e1.getMessage(), "OK", null);
}
if (success) {
// open dialog and have user provide name
try {
String tmpFilepath = FileSystemStorage.getInstance().getAppHomePath() + filename;
Dialog.show("Image File", tmpFilepath, "OK", null);
uploadImage(tmpFilepath, name);
} catch (IOException err) {
Log.p("Image Upload Failed:" + err.getMessage());
Dialog.show("Picture Uploaded Failed", "Something prevented the upload of the image.", "OK", null);
}
}
}
}
}
}
I purposely cut out a lot of the surrounding code in the above snippet to focus on what I believe to be important.
I left in the Dialog statements that I am using for debugging so I can see what the path is on the device. If I run this in the simulator, and choose a file, it uploads fine, but when I run it on an iPhone, the file sent to the server has 0 bytes, and the Dialog in the uploadImage method will display that '0 photo(s) uploaded'. When using Storage.g.entrySize() on "tempfile.png" it displays the file has not being 0 in size. How can I properly reference this file to send it to the server.
You are saving the gallery image to Storage but the upload method works with FileSystemStorage those aren't compatible so you get incompatible behaviors.

ImageViewer isnot working fine codenameone

I have a couple of questions regarding image viewer.
1)ImageViewer autoslides isnot working.The imageViewer works initially when the app is first started. But as soon as any other form is opened & then going back to the form containing imageViewer, the autoslide doesnt work.
Code for img viewer auto slide
placeholderForTable = (EncodedImage) theme.getImage("placeholderWithAnimate.png");
placeholderForTable = placeholderForTable.scaledEncoded(screenWidth, 30 + (screenWidth * 1 / 3));
BusinessForumImagesConnection bfic = new BusinessForumImagesConnection();
bfic.businessForumImagesConnectionMethod(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
DefaultListModel<Image> images;
if (bfic.response != null) {
for (Map<String, Object> entrySet : bfic.response) {
String imgUrl = (String) entrySet.get("imgUrl");
Image adImage = URLImage.createToStorage(placeholderForTable, imgUrl.substring(0, imgUrl.lastIndexOf(".")), + imgUrl, URLImage.RESIZE_SCALE);
adsSlideImagesArray.add(adImage);
}
}
ImageViewer imv = new ImageViewer();
Container adsContainer = BoxLayout.encloseY(imv);
if (adsSlideImagesArray != null) {
slideIndex = 0;
images = new DefaultListModel<>(adsSlideImagesArray);
imv.setImage(images.getItemAt(0));
imv.setImageList(images);
imv.setSwipePlaceholder(Image.createImage(100, 100));
Runnable r = new Runnable() {
public void run() {
if (slideIndex < images.getSize()) {
nextImage = (Image) images.getItemAt(slideIndex);
if (nextImage != null) {
imv.setImage(nextImage);
}
slideIndex++;
} else {
slideIndex = 0;
}
}
};
if (uITimer == null) {
uITimer = new UITimer(r);
}
if (uITimer != null) {
uITimer.schedule(5000, true, f); //5 seconds
}
}
});
2) Some random images are not always displayed in image viewer. It happens in both simulator & real devices. I have checked if the UrlImage is cached or not in storage. There are all the file saved but some of them are never displayed in image viewer.
Instead of image Viewer, i set the image icon in label and loop them. All the labels have their respective icons, but there is a problem in imageViewer. Code is same as above.
Make sure your timer fires and that no one canceled it.
Do you see the placeholder instead of the image? Details like that are essential.
Images that are deeper within the image viewer stack won't be pre-fetched. Notice that URLImage wasn't designed for the image viewer and is probably a bad idea for it as URLImage resizes the images. We recommend using a download method to get full sized images for the image viewer see this old post: https://www.codenameone.com/blog/image-viewer-from-the-web.html

FileSystemStorage isDirectory returns false for a directory

I am trying to write a file browser in CN1 to let the user select a profile picture for upload.
I tried using the FileSystemStorage's isDirectory() method, but it is returning false for a directory.
Code:
private void displayFiles(final Container c, String root)
{
c.removeAll();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
String files[] = fs.listFiles(root);
for(final String file: files)
{
System.out.println(file+"-->"+fs.isDirectory(file));
if(fs.isDirectory(file))
{
Button b = new Button("Folder::"+file);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
displayFiles(c, file);
}
});
c.addComponent(b);
}else
{
Container c1 = new Container(new BoxLayout(BoxLayout.X_AXIS));
Label l = new Label("File::"+file);
CheckBox cb = new CheckBox();
c1.addComponent(l);
c1.addComponent(cb);
c.addComponent(c1);
}
}
} catch (IOException ex) {
}
c.revalidate();
}
Output:
CN1Log__$-->false
CN1Preferences-->false
Cookies-->false
data-->false
FaceBookAccesstmp652635968-->false
folder1-->false
folder2-->false
HELLOCN1FS-->false
myFileName-->false
token-->false
Screenshot of the emulator:
Screenshot of the explorer
The behavior is same on the phone as well
Could this be a bug ?
Is there something that I am not doing correctly ?
Thanks
You need to use the full path for the file:
if(fs.isDirectory(root + file))

Resources