CardView Click to download PDF - java

i want to download a pdf file when i click on the card view, this is how i declare it inside a viewholder..
holder.pdfLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
baptistDatabase.child(post_key).child("pdflocation").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String baptistpdf = dataSnapshot.getValue(String.class);
Uri uri = Uri.parse(baptistpdf);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = dm.enqueue(request);
}
and this is my LogCat
FATAL EXCEPTION: main
Process: com.packageone.winter.tkpchanmariunitaizawl, PID: 13072
java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:475)
at android.net.Uri$StringUri.<init>(Uri.java:465)
at android.net.Uri.parse(Uri.java:437)
at com.packageone.winter.tkpchanmariunitaizawl.BaptistS_pdf.BaptistPdfFiles$1$2$1.onDataChange(BaptistPdfFiles.java:108)
My Database Goes like this.
Baptists -> Pdf Files -> push() -> (key)pdflocation - "Storage Location Link"
How i want is when i Click on the Card view, i just want to Download the Pdf, because i just cant refer to one single Link as it keeps on changing when a new pdf files are uploaded..
Help...

Related

How to Direct download from RecyclerView items(Firebase url)? Can't make it work

I'm fetching some Firebase files and I'm listing them with RecyclerView, I want to download one of those files when i click in a download button in the ListItem, not by redirecting to the url but direct downloading.
I've tried different kind of ways to achieve this but anything just doesn't seem to work, I've tried download-manager, AsyncTask but any of those either won't work or will crash the app, I've configured android permissions in the manifest file so the problem is not there, it's frustrating, if anyone could give me some help because I'm stuck here. Below my code
public class MaterialiAdapter extends RecyclerView .Adapter<MaterialiAdapter.MaterialiViewHolder> {
Context context;
ArrayList<Upload> uploadMateriali;
public MaterialiAdapter(Context c, ArrayList<Upload> u){
context=c;
uploadMateriali=u;
}
#NonNull
#Override
public MaterialiViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
return new MaterialiViewHolder(LayoutInflater.from(context).inflate(R.layout.recycler_materiali,parent,false));
}
#Override
public void onBindViewHolder(#NonNull final MaterialiViewHolder materialiViewHolder, final int i) {
materialiViewHolder.txtEmri.setText(uploadMateriali.get(i).getEmriMateriali());
materialiViewHolder.txtUrl.setText(uploadMateriali.get(i).getDateMateriali());
final String url=uploadMateriali.get(i).getUrlMateriali();
final String name=uploadMateriali.get(i).getEmriMateriali();
materialiViewHolder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDownload(url,name);
}
});
}
private void startDownload(String url, String fileName) {
Uri uri = Uri.parse(url);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); // Tell on which network you want to download file.
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // This will show notification on top when downloading the file.
request.setTitle("Downloading a file");
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); // Storage directory path
downloadManager.enqueue(request);
}
#Override
public int getItemCount() {
return uploadMateriali.size();
}
class MaterialiViewHolder extends RecyclerView.ViewHolder {
ImageView download;
ImageView delete;
TextView txtEmri;
TextView txtUrl;
public MaterialiViewHolder(#NonNull View itemView) {
super(itemView);
download = itemView.findViewById(R.id.imgDownMateriali);
delete = itemView.findViewById(R.id.imgDelMateriali);
txtEmri = itemView.findViewById(R.id.txtMaterialiName);
txtUrl = itemView.findViewById(R.id.txtMaterialiDate);
}
}
}
So the code that I currently have has a download-manager implemented, and that just won't work it will crash the app, it might be because of the context(non activity class), I don't know any more..
Logcat:
06-10 07:47:09.631 1119-1119/com.example.studentsapplication
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.studentsapplication, PID: 1119
java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:470)
at android.net.Uri$StringUri.<init>(Uri.java:460)
at android.net.Uri.parse(Uri.java:432)
at com.example.studentsapplication.MaterialiAdapter.startDownload(MaterialiAdapter.java:68)
at com.example.studentsapplication.MaterialiAdapter.access$000(MaterialiAdapter.java:34)
at com.example.studentsapplication.MaterialiAdapter$1.onClick(MaterialiAdapter.java:60)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

Load image from firebase storage into image view

In my app users are able to send text and images to other users and now i also want when a user clicks on the sent or received image they will be taken to another activity were the image will be loaded into an image view for the user.
So i added a click listener to the image in my adapter like this
void bind(Messages message) {
String message_type = message.getType();
String user_id = message.getFrom();
String msg_id = message.getKey();
if (message_type.equals("text")) {
messageText.setText(message.getMessage());
// Format the stored timestamp into a readable String using method.
timeText.setText(DateUtils.formatDateTime(message.getTime()));
// DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(user_id).child()
recieved_image.setVisibility(View.INVISIBLE);
// nameText.setText(message.getSender().getNickname());
// Insert the profile image from the URL into the ImageView.
// Utils.displayRoundImageFromUrl(mContext, message.getSender().getProfileUrl(), profileImage);
}else {
messageText.setVisibility(View.INVISIBLE);
recieved_image.setVisibility(View.VISIBLE);
Picasso.with(recieved_image.getContext()).load(message.getMessage()).into(recieved_image);
recieved_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MessageImageViewerActivity.class);
intent.putExtra("message_id",msg_id);
view.getContext().startActivity(intent);
}
});
with the aim of transferring the message id to the next activity which should be used to locate and load the image from firebase storage like this
msgImage = findViewById(R.id.MsgImageView);
mAuth = FirebaseAuth.getInstance();
final String message_id = getIntent().getStringExtra("message_id");
mRootRef = FirebaseDatabase.getInstance().getReference();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mImageStorage.child("message_images").child(message_id).getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
String ima = task.getResult().toString();
// Picasso.with(MessageImageViewerActivity.this).load(ima).into(msgImage);
Glide.with(MessageImageViewerActivity.this)
.load(ima)
.into(msgImage);
}
}
});
but it is returning an error that the path is invalid. this is the logcat error message.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.storage.StorageReference com.google.firebase.storage.StorageReference.child(java.lang.String)' on a null object reference
at com.mani.eric.quickchat.ui.MessageImageViewerActivity.onCreate(MessageImageViewerActivity.java:60)
at android.app.Activity.performCreate(Activity.java:7327)
at android.app.Activity.performCreate(Activity.java:7318)
please what I'm trying to do, is it possible?
or what I'm i not doing right.
You need to do the following:
StorageReference mImageStorage = FirebaseStorage.getInstance().getReference();
First get the reference to the firebase storage, then access the child that you created in the firebase storage console.
mImageStorage.child("message_images").child(message_id).getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
String ima = task.getResult().toString();
// Picasso.with(MessageImageViewerActivity.this).load(ima).into(msgImage);
Glide.with(MessageImageViewerActivity.this)
.load(ima)
.into(msgImage);
}
}
});

WebView Download Manager: How to download files with their default names?

I'm developing a simple webview app using Android Studio. The webview app is booting a website that contains downloadable media files. For now, after downloading a file it save the file as fileName.
This is my Download manager
String myCurrentUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
superWebView = findViewById(R.id.myWebView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://www.hausadownload.blogspot.com");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new WebViewClient(){});
superWebView.setWebChromeClient(new WebChromeClient());
superWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(MainActivity.this, "Your file is downloading...", Toast.LENGTH_SHORT).show();
}
});
}
I don't want it to be saving all files with the name "fileName". I want it to be saving files with their default names
You should somehow be able to get the file name from the url like so:
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
Then just pass that in this line instead of hardcoded String "filename":
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

Best way to get the downloadUrl of thumbnail generated by Firebase Cloud Function

StorageReference newfilepath = mStorage.child("User Submission Images").child(user_id).child("photo1g.jpg");
newfilepath.putFile(photo1ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
final Uri dwnldUri = task.getResult().getDownloadUrl();
businessDBRef.child(user_id).child("photos1").setValue(dwnldUri.toString());
StorageReference thumbpath = mStorage.child("User Submission Images").child(user_id);
thumbpath.child("thumb_photo1v.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
businessDBRef.child(user_id).child("thumb1").setValue(uri.toString());
}
});
mProgess.dismiss();
Toast.makeText(getApplicationContext(), "Upload Successful", Toast.LENGTH_SHORT).show();
}
});
After the image gets uploaded i try to pass the download url of the thumbnail into the database but i assume that my code executes faster than the creation of the thumbnail so i get this
StorageException has occurred.
Object does not exist at location.
When checking the Firebase storage the thumbnail is there with the download url accessible. Is there any workaround for this? maybe a way to wait for the thumbnail to generate first and then get the download URl??

Loading PDF from internal storage Error invalid format

So I've been practising download manager and i was trying out some program.
A first button will download a said Pdf to a location in my phone.
The second button is supposed to open the Pdf file with a Pdf reader installed by the user such as WP Reader etc..
The download works fine, but when i open the pdf , it says invalid format.
I uploaded a sample Pdf to the google drive , so I know that the uploaded file isnt corrupted in any case. There muse be some problem when the file is being downloaded from the server. Please help me find the mistake. And I am relatively new to Android.
And the download button uses an Onclicklistener while the loadPdf is given in the xml file android:onClick="downloadPdf" .
public class MainActivity extends AppCompatActivity {
String myHTTPUrl = "https://drive.google.com/open?id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU";
String TAG = "My app";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button download = (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"download method called");
downloadPdf();
Toast.makeText(MainActivity.this,"Listener Called",Toast.LENGTH_SHORT).show();
Log.v(TAG,"On Click Listener Called");
}
});
}
public void loadPdf(View view) {
Log.v(TAG,"Pdf load called");
File pdfFile = new File(Environment.getExternalStorageDirectory()+"/notes","ssp.pdf");
if(pdfFile.exists())
{
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent intent = Intent.createChooser(pdfIntent, "Open File");
try
{
startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(MainActivity.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(MainActivity.this,"Pdf not found",Toast.LENGTH_SHORT).show();
}
}
public void downloadPdf()
{
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl));
request.setTitle("Solid State Physics");
request.setDescription("File is being Downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/notes","ssp.pdf");
manager.enqueue(request);
}}
EDITED :
This is the exact error I'm facing with screenshot
Error : File format error , Cannot be opened
Screenshot of the error.
You're not downloading the PDF, you're downloading the web-page displaying the contents of the PDF. If you want to download the PDF file directly, use the following URL:
String myHTTPUrl = "https://drive.google.com/uc?export=download&id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU";
and your application should work.
(Don't forget to delete the invalid notes/ssp.pdf file first, otherwise the DownloadManager will download the file under a different name, like notes/ssp-1.pdf.)

Categories

Resources