Viewing pdf files in Android Webview from url - android

I'm trying to open a pdf file in a Android WebView from this url:
http://bijsluiters.fagg-afmps.be/registrationSearchServlet?key=BE-TU441865&leafletType=leafletNL
When i searched for information online on how to achieve this, i found that
you need to extend the url with this in front of it: "http://docs.google.com/gview?embedded=true&url="
but when i do this, i can only see html like when you open the link in a browser:
"https://docs.google.com/gview?embedded=true&url=http://bijsluiters.fagg-afmps.be/registrationSearchServlet?key=BE-TU441865&leafletType=leafletNL"
How can i see the actual non-html content in my webview?
public class BijsluiterFragment : Android.Support.V4.App.Fragment
{
//Title = DomainController.Instance.GetWord("BijsluiterTitle");
private View view;
private WebView webview;
private string url;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.Inflate (Resource.Layout.BijsluiterFragment, container, false);
webview = view.FindViewById<WebView> (Resource.Id.webView);
webview.Settings.JavaScriptEnabled=true;
webview.Settings.SetPluginState (WebSettings.PluginState.On);
if(!String.IsNullOrEmpty(url))
{
webview.LoadUrl ("http://docs.google.com/gview?embedded=true&url="+url);
}
return view;
}
public void SetUrl(string url)
{
this.url = url;
}
}
I also tried with the 'loadwithbaseurl' method but it didn't work either...

I solved the same problem with this:
if (url.endsWith(".pdf")) {
try {
String urlEncoded = URLEncoder.encode(url, "UTF-8");
url = "http://docs.google.com/viewer?url=" + urlEncoded;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
With this prefix: "http://docs.google.com/viewer?url=" the WebView open the pdf with GoogleDocs.
Hope it helps you!!

Related

Api calls from a fragment using Volley

I am making API calls from my fragment and getting the response using volley. The API calls are made again every time I click on that fragment tab. I want the API call to take place only once. Is there any way to achieve this? I tried searching for the solution but did not find anything useful. Below is the code of my fragment.
public class Tab3News extends Fragment {
private RecyclerView newsView;
private NewsAdapter newsadapter;
String myxmlResponse;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Making request again","hello");
View layout = inflater.inflate(R.layout.tab3news, container, false);
newsView = (RecyclerView) layout.findViewById(R.id.newstable);
String symPassed = ((SendString)getActivity()).message;
String XmlURL = "http://demoapplication-env.us-east-2.elasticbeanstalk.com/?symbol="+symPassed+"&indicator=XML";
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
StringRequest req = new StringRequest(Request.Method.GET, XmlURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
//processData(response);
myxmlResponse = response;
newsView.setHasFixedSize(true);
//newsView.setItemAnimator(new DefaultItemAnimator());
newsView.setLayoutManager(new LinearLayoutManager(getActivity()));
newsView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
newsadapter = new NewsAdapter(getActivity(),getData());
newsView.setAdapter(newsadapter);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// handle error response
}
}
);
queue.add(req);
return layout;
}
}
There are two ways to do this-
1- Call the API from the parent activity of this fragment and accordingly pass the data to the fragment using 'setArguments(bundle)', by doing this, your API would not get called everytime on loading of the fragment.
2- Keep a boolean value in the Preference whenever the API is called-
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
mMyPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstTime = mMyPrefs.getBoolean("IS_FIRST_TIME", true);
if (mIsFirstTime)
{
SharedPreferences.Editor editPrefs = mMyPrefs.edit();
editPrefs.putBoolean("IS_FIRST_TIME", false);
editPrefs.apply();
callAPI();
}
else
{
//TO DO YOUR STUFF
}
}
I think it is better to call the api in activity and pass the arguments through bundle rather than using a flag in shared preference. Then again, its my personal opinion.

Android Fragment Manager Null Object Reference

#JavascriptInterface
public void switchView() {
//sync the BottomBar Icons since a different Thread is running
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run()
{
MapFragment mapFragment = new MapFragment();
FragmentManager fragmentManager = ((MainActivity) mContext).getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, mapFragment);
transaction.commit();
}
});
}
When i run this code everything is fine, but when i add the line
mapFragment.setUrl("www.examplestuff.com");
the app crashes with Attempt to invoke virtual method 'void android.webkit.WebView.loadUrl(java.lang.String)' on a null object reference
My Fragment class looks like this
public WebView mapView;
private String thisURL;
public void setUrl(String url) {
thisURL = url;
mapView.loadUrl(thisURL);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map,container, false);
mapView = (WebView)view.findViewById(R.id.mapView);
this.setUrl("file:///android_asset/www/MapView.html");
mapView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mapView.getSettings();
webSettings.setJavaScriptEnabled(true);
//allow cross origin - like jsonP
webSettings.setAllowUniversalAccessFromFileURLs(true);
return view;
}
Also call there the method this.setURL() and works fine.
What I am doing wrong?
Has the FragmentManager no access of the instance WebView of the fragment???
This be because when you call setUrl it invokes this method:
public void setUrl(String url) {
thisURL = url;
mapView.loadUrl(thisURL);
}
the line mapView.loadUrl(thisURL); accesses the mapView. However you are likely calling setUrl before the Android system has called onCreateView, therefore mapView is null, causing said crash.
public void setUrl(String url) {
thisURL = url;
if(mapView != null) {
mapView.loadUrl(thisURL);
}
}
and
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map,container, false);
mapView = (WebView)view.findViewById(R.id.mapView);
if(thisUrl != null) {
mapView.loadUrl(thisURL);
}
... other code
Then mapFragment.setUrl("www.examplestuff.com"); would work
A better solution would be to understand more the Activity & Fragment lifecycles and not call setUrl when the Fragment is in an invalid state :-) You are probably calling setUrl when really you should be passing the Url as an intent extra when the fragment is created. https://developer.android.com/training/basics/fragments/communicating.html

Android: unable to lauch new Activity from an inner class

Android: someone help:
I notice this kind of question has been asked before by other people but the answers have not been useful to my my case; I need to launch a new activity from an inner
class but all I get is the error bellow:
04-05 15:00:43.851: E/AndroidRuntime(3288): Caused by: java.lang.InstantiationException: com.school.School$StudentProfile
Here is my code snippet:
public class School extends Activity{
ProgressDialogue progressDialogue;
protected WebViewTask _webTask;
String path = "http://www.school.com/student/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.school);
progressDialogue = new ProgressDialogue(School.this);
_webTask = new WebViewTask();
_webTask.execute();
}
//rest of the code
/** The inner class */
public class StudentProfile {
Context context;
/** Instantiate the interface and set the context */
public StudentProfile(Context c) {
context=c;
}
/** launch student activity */
public void lauchProfile() {
School.this.startActivity(new Intent(School.this, StudentProfile.class));
//Intent intent = new Intent(School.this, StudentProfile.class);
//startActivity(intent);
}
}
void webView(){
String url = path +"student.php";
WebView wv = (WebView) findViewById(R.id.trivia_webview);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.addJavascriptInterface(new StudentProfile (this), "Student");
wv.loadUrl(url);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// open URL in the web view itself
if (url.contains(url))
return super.shouldOverrideUrlLoading(view, url);
// open URL in an external web browser
else {
return true;
}
}
});
}
// rest of the code
NOTE: there is a 'student' button on the web view that is supposed to launch the StudentProfile activity.
Your StudentProfile is not an Activity, so you can not start it that way. It needs to be a separate class, and declared in AndroidManifest.xml.

mono for android get html source code

I want to get html source code in c# (mono for android)
I add webview in my project. webview name is web.
my code:
WebView webView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main); webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetSupportZoom(true);
webView.Settings.BuiltInZoomControls = true;
webView.Settings.LoadWithOverviewMode = true; //Load 100% zoomed out
webView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
webView.ScrollbarFadingEnabled = true;
webView.VerticalScrollBarEnabled = true;
webView.HorizontalScrollBarEnabled = true;
webView.SetWebViewClient(new AwesomeWebClient());
webView.SetWebChromeClient(new AwesomeWebChromeClient(this));
webView.LoadUrl(#"http://www.google.com");
}
private class AwesomeWebClient : WebViewClient { }
private class AwesomeWebChromeClient : WebChromeClient
{
private Activity mParentActivity;
private string mTitle;
private string username;
private string password;
private string oldurl="";
public AwesomeWebChromeClient(Activity parentActivity)
{
mParentActivity = parentActivity;
mTitle = parentActivity.Title;
}
public override void OnProgressChanged(WebView view, int newProgress)
{
mParentActivity.Title = string.Format("Loading {0}%", newProgress);
mParentActivity.SetProgress(newProgress * 100);
if (newProgress==100) mParentActivity.Title=mTitle;
}
}
I open www.google.com in webview component and I want to see html source code
I don't believe that there is a way to obtain the HTML from the WebView.
Instead, you should grab the HTML yourself with a WebRequest, e.g. this handy StackOverflow answer.

load textfile in webview android

so far i have read how to load "normal" html webpages in a webview ..
so far I pass the URL containing the path of my text file but it loads nothing.
this is my method:
#Override
public void onSelected(String url) {
ViewerFragment viewer = (ViewerFragment) getSupportFragmentManager()
.findFragmentById(R.id.view_fragment);
if (viewer == null || !viewer.isInLayout()) {
Intent showContent = new Intent(getApplicationContext(),
ViewerFragment.class);
showContent.setData(Uri.parse(url));
startActivity(showContent);
} else {
viewer.updateUrl(url);
}
}
and the viewer fragment got this:
public class ViewerFragment extends Fragment{
private WebView viewer = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
viewer = (WebView) inflater
.inflate(R.layout.details_fragment, container, false);
return viewer;
}
public void updateUrl(String newUrl) {
if (viewer != null) {
viewer.loadUrl(newUrl);
}
}
}
but keep getting this screen:
any ideas how to do this? =/ I already tried googling a bit but didnt find much info about it... actually found almost none. So any help would be appreciated.
Try reading the contents of the text file and prefixing the text with <html><body> then append </body></html> then use the WebView method loadData(...).
Example:
StringBuilder sb = new StringBuilder("<html><body>");
sb.append(readTextFile());
sb.append("</body></html>");
myWebView.loadData(sb.ToString(), "text/html", "UTF-8");
public String readTextFile(String filename) {
// Open and read the contents of <filename> into
// a single string then return it
}

Categories

Resources