Show office document in android - java

I am developing an android blog app with Firebase Firestore. I want to show a Microsoft Office Word document in the app (because I want to add multiple styled texts).
When the user clicks on an article in the app, an activity will show the specified data. What I mean is that there will be different texts, so each article will have different content. What I want is to show styled text like the ones available in Microsoft Word (bullets and numbering, bold, italic... these stuff) in the content of the article.
I thought of uploading a word.docx document into the storage in Firebase and adding the link of it in the content field in Firestore. But I am sure that it will not work.
Does anyone know what should I do?

I have similar thing the only difference is I have shown pdf, but I am sure it can be done for doc also, you will need webView to make it work, I am providing you method that will open the file in webview by google docs, have a look:
private void setUpWebView() {
setWebviewSettings();
mwebView.clearHistory();
mwebView.clearFormData();
mwebView.clearCache(false);
mwebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mwebView.setScrollbarFadingEnabled(true);
mwebView.getSettings().setSupportZoom(true);
mwebView.setWebChromeClient(new CustomWebChromeClient(this));
mwebView.setWebViewClient(new WebViewClient());
mwebView.getSettings().setJavaScriptEnabled(true);
mwebView.getSettings().setPluginState(WebSettings.PluginState.ON);
String url = AppConstants.FULL_TANDC_URL;
if (NetworkUtil.isNetworkAvailable(this)) {
if (url != null && !TextUtils.isEmpty(url) && URLUtil.isValidUrl(url)) {
textNoData.setVisibility(View.GONE);
if (url.contains(".pdf")) {
mwebView.loadUrl("http://docs.google.com/gview?embedded=true&url=" + url);
mprogressBar.setVisibility(View.GONE);
} else {
mwebView.loadUrl(url);
mprogressBar.setVisibility(View.VISIBLE);
}
} else {
textNoData.setVisibility(View.VISIBLE);
mprogressBar.setVisibility(View.GONE);
}
} else {
mprogressBar.setVisibility(View.GONE);
textNoData.setVisibility(View.VISIBLE);
}
}
I hope this will help you.
Happy coding :)

Related

Android Webview cannot render the pdf sometimes and shows blank/white page instead

Open the pdf in the webview using google docs
Open the same pdf or different pdf again and again.
Sometimes it will show the blank/white page in the android untill we refresh the webpage again for 1 or 2 times.
I have made the sample on the pdf. The link for the project is shown below:
https://github.com/gopalawasthi123/PdfWebView
Hope this will help you Better.
public void SetWebView(WebView webview,string externalUrl){
webview.Tag = "webview";
webview.Settings.JavaScriptEnabled = true;
webview.Settings.SupportZoom ();
webview.Settings.SetAppCacheEnabled(true);
webview.Settings.DomStorageEnabled = true;
webview.ZoomOut ();
webview.ZoomIn ();
webview.Settings.BuiltInZoomControls = true;
webview.Settings.LoadWithOverviewMode = true;
webview.Settings.UseWideViewPort = true;
//webview.Settings.SetSupportZoom (true);
webview.Settings.SetPluginState (WebSettings.PluginState.On);
webview.Settings.GetPluginState ();
if (externalUrl.StartsWith("http://") || externalUrl.StartsWith("https://"))
webview.LoadUrl (externalUrl);
webview.SetWebViewClient (new MonkeyWebViewClient (imgViewBack, imgViewForward, imgRefresh));
webview.SetWebChromeClient (new WebChromeClient ());
}
You can reload the page until it displays the pdf in this way:
public void onPageFinished(WebView view, String url) {
if (view.getTitle().equals(""))
view.reload();
}
After testing second PDF URL file, WebView seems like that can not load large PDF file.
Reason:
WebView display HTML. The fact that this works at all is by a hack- google will convert simple PDFs into HTML. It doesn't seem like they support anything that big. Even if they did, I would expect loading a large page PDF converted to HTML would be so large I highly doubt you'd be able to load it without going OOM. Use an appropriate PDF library, make a real PDF rendering view, and make sure not to render more of the PDF at a time than you need (or else you'll go OOM anyway). In other words, don't rely on hacky solutions you never should have relied on in the first place.
Solution:
You should try alternatives like PDF.js running locally in your device, instead of a service like Google Docs preview.(Or download PDF first to local file path)
Put it in your assets folder and tweak the example:
wv.loadUrl("file:///android_asset/web/viewer.html");
Also, you can have Out Of Memory situations. An alternative to try is a native viewer like AndroidPdfViewer.
We can solve the Problem in the two ways.
1. One is to use the Js.Pdf Plugin on the server end. It surely solve the problem but if we have multiple pdf's in the Fragment then it may cause the out of memory situations
and app can crash.
2. Second option is we can recursively called the function to load webview. This will also cause the issue but with less frequency Below is the code:
private void showPdf(final String imageString) {
pdfView.invalidate();
pdfView.getSettings().setJavaScriptEnabled(true);
pdfView.getSettings().setSupportZoom(true);
pdfView.loadUrl("http://docs.google.com/gview?embedded=true&url=" + imageString);
pdfView.setWebViewClient(new WebViewClient() {
boolean checkhasOnPageStarted = false;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
checkhasOnPageStarted = true;
}
#Override
public void onPageFinished(WebView view, String url) {
if (checkhasOnPageStarted ) {
pdfView.loadUrl(removePdfTopIcon);
} else {
showPdf(imageString);
}
}
});
}
I was having the exact same issue and found that there was always a chance the WebView would not load on the first load attempt, especially if the pdf was on the larger side. The code I put together below works 100% of the time. From my beginner's understanding, it safely utilizes a separate thread to loop through and test the load status of the WebView, re-attempting a load of the view until successful. As this question was posted a year ago, I have generalized my solution to best benefit new viewers.
public class WebViewActivity extends AppCompatActivity {
String PDFView;
WebView webView;
String PDFBrowserView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the intended "PDFView"
PDFView = getIntent().getExtras().get("PDFView").toString();
//Have to manually encode (?) the url to display it
try {
PDFView = URLEncoder.encode(PDFView, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Full display url
PDFBrowserView = "https://docs.google.com/gview?embedded=true&url=" + PDFView;
//Initialize a new "WebView" instance
webView = new WebView(WebViewActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
//This handles callbacks (?)
webView.setWebChromeClient(new WebChromeClient());
//Call this to load page if page is blank with pdf url until page is not blank
checkPageFinished();
}
public void checkPageFinished() {
//If view is blank:
if (webView.getContentHeight() == 0) {
//Run off main thread to control delay
webView.postDelayed(new Runnable() {
#Override
public void run() {
//Load url into the "WebView"
webView.loadUrl(PDFBrowserView);
}
//Set 1s delay to give the view a longer chance to load before
// setting the view (or more likely to display blank)
}, 1000);
//Set the view with the selected pdf
setContentView(webView);
webView.postDelayed(new Runnable() {
#Override
public void run() {
//If view is still blank:
if (webView.getContentHeight() == 0) {
//Loop until it works
checkPageFinished();
}
}
//Safely loop this function after 1.5s delay if page is not loaded
}, 1500);
}
}
}
There are some ways through which we can identify whether a Page/URL is loaded properly or not from onPageFinished() method of the Webview and based on that reload() url.
Option 1 : To check with contentHeight of the webview.
override fun onPageFinished(view: WebView?, url: String?) {
if(view?.contentHeight == 0){
view?.reload()
return
}
super.onPageFinished(view, url)
}
Option 2 : To check with title of the webview.
override fun onPageFinished(view: WebView?, url: String?) {
if(view?.title.isNullOrEmpty()){
view?.reload()
return
}
super.onPageFinished(view, url)
}
Tested in multiple devices and working within API 29
in Kotlin
val webSettings: WebSettings = webview.settings
webSettings.javaScriptEnabled = true
webSettings.useWideViewPort = true
webSettings.loadWithOverviewMode = true
webSettings.domStorageEnabled = true
webview.webViewClient = AppWebViewClients()
// val TERM_CONDITION_URL = "http://docs.google.com/gview?embedded=true&url="
// + "YOUR_DOC_URL_HERE"
bindind?.webview?.loadUrl(TERM_CONDITION_URL)
and here AppWebViewClients class
class AppWebViewClients : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
view.loadUrl(url)
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
if (view?.contentHeight == 0)
view?.reload();
else {
super.onPageFinished(view, url)
}
}
}
I think you should do as below:
public void onPageFinished(WebView view, String url) {
if (!view.getUrl().equals(url)) {
view.loadUrl(url);
return;
}
}

How to get a shared link of recently uploaded file when using box in Android?

How can I get a shared link of a recently uploaded file when using box in Android.
mFileApi.getCreateSharedLinkRequest(fileId).setCanDownload(true)
.setAccess(BoxSharedLink.Access.OPEN)
.toTask().addOnCompletedListener(new BoxFutureTask.OnCompletedListener<BoxFile>() {
#Override
public void onCompleted(BoxResponse<BoxFile> response) {
if (response.isSuccess()) {
BoxFile boxFile = response.getResult();
String downloadUrl = boxFile.getSharedLink().getDownloadURL();
Log.e("downloadurl", "onCompleted: " + downloadUrl);
//This return me a web link to show the Box page to download the file
} else {
Toast.makeText(MainActivity.this, "error while getting sharelink", Toast.LENGTH_SHORT).show();
}
}
}).run();
You must first create the link, it is not created automatically. See this answer how to do it: How to create shared link in box using java sdk

android WebView shouldOverrideUrlLoading()

Hi this doesnt work for me:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
s="url clicked: "+url;
view.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
return true;
}
});
I have links in my html, it shows during loading in main activity,
but when I click them I get a white blank screen
I want to be able to read what those urls are, in the program, and I assume this url override function is the purpose for this.
I have tried with loadData() as well.
Thank you
You're not passing the new url to the WebView.
Should be
view.loadDataWithBaseURL(url, null, "text/html", "utf-8", null);
Edit: This also gives me a blank screen because loadDataWithBaseUrl expects you to provide some text or html as the data parameter yourself. Just use
view.loadUrl(url);
I didn't write http:// in my links, and wrote only x. This was the problem, it works now.

Android Launcher3 - Google Now Page

I downloaded Launcher3 (Google's Kitkat Launcher) from 4.4 Sources.
I imported it into eclipse . I got rid of errors.And my launcher works pretty good.
But something missing. "GOOGLE NOW" page when you scroll to left.
I can't activate google now.Anyway i don't need that. I want to put my own fragment or layout into first page and other pages will work same like normal launcher.
Like a Google's experience Launcher(Kitkat Launcher of google)'s Google Now page ..
Like this :
I added my layout like this :
here is original codes from workspace.java
public long insertNewWorkspaceScreen(long screenId, int insertIndex) {
if (mWorkspaceScreens.containsKey(screenId)) {
throw new RuntimeException("Screen id " + screenId + " already exists!");
}
CellLayout newScreen = (CellLayout)
mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, null);
newScreen.setOnLongClickListener(mLongClickListener);
newScreen.setOnClickListener(mLauncher);
newScreen.setSoundEffectsEnabled(false);
mWorkspaceScreens.put(screenId, newScreen);
mScreenOrder.add(insertIndex, screenId);
addView(newScreen, insertIndex);
return screenId;
}
here is edited codes by me on workspace.java
public long insertNewWorkspaceScreen(long screenId, int insertIndex) {
if (mWorkspaceScreens.containsKey(screenId)) {
throw new RuntimeException("Screen id " + screenId + " already exists!");
}
if (screenId == 2) //Firstscreen/page
{
RelativeLayout newScreen = (RelativeLayout)
mLauncher.getLayoutInflater().inflate(R.layout.blinkfeed, null);
newScreen.setOnClickListener(mLongClickListener);
newScreen.setOnClickListener(mLauncher);
newScreen.setSoundEffectsEnabled(false);
// mWorkspaceScreens.put(screenId, newScreen);
mScreenOrder.add(insertIndex, screenId);
addView(newScreen, insertIndex);
return screenId;
}
else
{
CellLayout newScreen = (CellLayout)
mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, null);
newScreen.setOnLongClickListener(mLongClickListener);
newScreen.setOnClickListener(mLauncher);
newScreen.setSoundEffectsEnabled(false);
mWorkspaceScreens.put(screenId, newScreen);
mScreenOrder.add(insertIndex, screenId);
addView(newScreen, insertIndex);
return screenId;
}
}
as you can see when its first page i changed layout but i'm getting problems on childviews, animations etc,
anyway i cant even access other pages after that.
i putted everywhere try catch when i get errors because of "celllayout cannot bind to relative bla bla .."
my try catch like this
try
{
cell layout stuff its trying to make animations etc.
}
catch (Exception e)
{
//empty
}
i couldn't make it work at the moment like a google now pages :)
does anybody know about adding a fragment/layout into first page ?
Thanks.
If you want to add some fragment or view in the same manner as Google Now, the Launcher3 code supports that. You basically have 2 ways of getting the desired behavior:
Subclass the Launcher class and overwrite hasCustomContentToLeft() to return true and addCustomContentToLeft() where you can create/inflate your view to be added. Make sure you call addToCustomContentPage and implement the CustomContentCallbacks if you want to be notified when the screen is open.
Implement the same methods as described above in the Launcher class directly.
Hope this helps,
Mihai

Unable to create link with DBX chooser error android

I am attempting to integrate the Dropbox chooser drop-in api into my application. I am running into an abnormal issue. In my app when I launch the dbx chooser, anytime that I select a file the application fails with the following error code:
Sorry, an error has occurred. Please try again later.
Here is the portion of my code that implements the Dropbox API. This portion of the code is where the dropbox api is initially invoked.
public void StartDropboxApplication() {
// create the chooser
DbxChooser chooser = new DbxChooser(APP_KEY);
DbxChooser.ResultType result;
// determine which mode to be in // TODO REMOVE ALL BUT FILE CONTENT TODO SIMPLIFY by making this a setting
switch(( (RadioGroup) ParentActivity.findViewById(R.id.link_type)).getCheckedRadioButtonId() ) {
case R.id.link_type_content:
result = DbxChooser.ResultType.DIRECT_LINK;
break;
default:
throw new RuntimeException("Radio Group Related error.");
}
// launch the new activity
chooser.forResultType(result).launch(ParentActivity, 0);
}
Here is the position where the code should then pick it up although it never does.
protected void onActivityResult( int request, int result, Intent data ) {
Log.i(fileName, "result: " + result);
// check to see if the camera took a picture
if (request == 1) {
// check to see if the picture was successfully taken
if (result == Activity.RESULT_OK) {
onPicture();
} else {
Log.i(fileName, "Camera App cancelled.");
}
} else if (request == 0) {
if ( result == Activity.RESULT_OK ) {
onDropbox(data);
} else {
Log.i(fileName, "dropbox related issue.");
}
}
}
Thank you for any help or suggestions that you are able to provide.
I was able to solve my own issues and get this working. On the off chance that someone else has a similar problem I will detail the solution. The first issue was I was that my APP_KEY was incorrect.
The next issue was that I was attempting to read from a direct link instead of a content link. The direct link provides the application with a link to the file on the Dropbox server whereas the content link provides the application with a cached version of the file. If the file is not present on the device, the SDK downloads a copy for you.

Categories