load textfile in webview android - 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
}

Related

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

Fragment Rotation

I have the following piece of code which retrieve some weather data from the openweathermap api. The AsyncTask class is used for that purpose.
public class ForecastFragment extends Fragment {
String imageUrl;
ListView listView;
List<WeatherForecastData> WeatherForecastDataList;
String IMG_URL = "http://api.openweathermap.org/img/w/";
Fragment fragment;
public ForecastFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate xml view and convert it to a View object
View rootView = inflater.inflate(R.layout.fragment_forecast, container, false);
//Initialise ListView.
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String temp = WeatherForecastDataList.get(position).getWeatherTemperature();
Toast.makeText(getActivity(), temp + "° C"+" Have a nice day", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
//Now we are ready for further processing
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
if (savedInstanceState == null) {
if(isOnline()) {
requestData("http://api.openweathermap.org/data/2.5/forecast/daily?lat=50.09&lon=14.42&cnt=9&&units=metric&mode=json");
}else{
Toast.makeText(getActivity(),"There is no internet connection",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("ImageURL", imageUrl);
super.onSaveInstanceState(savedInstanceState);
}
//We create a MyTask object,and execute the async. thread with the specified url which is shown just above.
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
//AsyncTask that will do the asynchronous threading. It displays the weather's icon,description
//and temperature in the main thread via the OnPostExecute(...) method.
private class MyTask extends AsyncTask<String, String, List<WeatherForecastData>> {
#Override
protected void onPreExecute() {
//Used to initialise Views such as Progress Bars which are not needed for this
//project.
}
#Override
protected List<WeatherForecastData> doInBackground(String... params) {
//Read the url,specify the METHOD GET, and store it in content.
String content = HttpManager.getData(params[0]);
//JSON parsing of the openweather api's response. It is not hard,but I had to use the
//debugger quite a lot to make sure that I deserialise the correct JSON values into Strings.
WeatherForecastDataList = WeatherJSONParser.parseFeed(content);
//Fetching the url image
for (WeatherForecastData d : WeatherForecastDataList) {
try {
imageUrl = IMG_URL + d.getPhoto();
InputStream in = (InputStream) new URL(imageUrl).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
//Is it deprecated?
d.setBitmap(bitmap);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return WeatherForecastDataList;
}
//WeatherForecastData is the Object that contains all that instances we want to display.
#Override
protected void onPostExecute(List<WeatherForecastData> result) {
if (result == null) {
Toast.makeText(getActivity(), "There is some wrong,and data can not be displayed", Toast.LENGTH_LONG).show();
return;
}
WeatherForecastDataList = result;
//Display the ListView.
WeatherAdapter adapter = new WeatherAdapter(getActivity(), R.layout.weather_row, WeatherForecastDataList);
listView.setAdapter(adapter);
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
My question is how to make my async task class to work when phone rotates.In other words,I don't want my Fragment to be killed,but storing the weather get I get. I saw other questions here too,but I am confused in this part. Thank you.
Making config changes in the manifest is not the recommended way to save the instance of the fragment.
Instead, you should save the instance of the fragment in container activity's onSaveInstanceState() overriden method.
Below is a small snippet that will help you:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState,"fragmentInstanceSaved",getSupportFragmentManager().findFragmentById(R.id.fragment_container));
}
Now, in your container activity's onCreate method check if bundle is null or not:
if(savedInstanceState!=null){
Fragment fragment = getSupportFragmentManager().getFragment(savedInstanceState,"fragmentInstanceSaved");
//recreate your preserved fragment here
}else{
//goto ur default activity or fragment....
}

Viewing pdf files in Android Webview from url

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!!

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.

Progress bar with AsyncTask Object on initial app load

I have looked around on the API and through a few questions on here, and I think I am on the right path. My app is based on a webView object and the initial load has quite a few cached pages so I want progressDialog on the initial start up instead of the blank black screen. Right now the app just crashes but I believe it is because I am creating and calling the AsyncTask object in the wrong place. Right now it is being called in the onCreate() method. I’m not new to Java but I am new to Android and this idea of not working with a main() function is confusing to me.
So where should I call the execute() function if I only want the ProgressDialog shown on the initial launch? And is my AsyncTask object even set up correctly?
public class site extends Activity {
private WebView engine;
private String urlSave;
private WebViewClient yourWebClient;
private ProgressDialog initLoadDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
yourWebClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("tel:") == true) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
}
else if(url.contains(“blah") == true && url.contains(“blah2") == false) {
view.loadUrl(url);
}
else if(url.contains(“blah3") == true) {
double[] loc = getGPS();
url += "&cLat=" + loc[0] + "&cLong=" + loc[1];
view.loadUrl(url);
}
else {
/*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("url"));
startActivity(browserIntent);*/
}
return true;
}
};
}
#Override
public void onStart() {
progressSetup();
setContentView(R.layout.main);
}
public void progressSetup () {
initLoadDialog = new ProgressDialog(site.this);
initLoadDialog.setMessage("A message");
initLoadDialog.setIndeterminate(false);
initLoadDialog.setMax(100);
initLoadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
urlLoad loading = new urlLoad();
loading.execute();
}
private class urlLoad extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url) {
try {
engine = (WebView) findViewById(R.id.web_engine);
engine.getSettings().setJavaScriptEnabled(true);
engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setSupportZoom(true);
engine.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
engine.getSettings().setGeolocationEnabled(true);
engine.setWebViewClient(yourWebClient);
engine.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
engine.loadUrl(“albhal");
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
initLoadDialog.setProgress(engine.getProgress());
}
}
}
Check your adb log, the error will pretty much explain to you what you didn't do right.
There's a lot of bad practice in your code. For example you call setContentView() in two Methods with different Layouts. The Flow of a android application is to call "onCreate", then "onStart". There is no reason to distinguish between those methods for you. Merge them and decide which layout to populate.
Also it is recommended to change the user-interface (this means also the dialogs) through the managing activity. In your case you are creating a ProgressDialog in the activity which then gets modified by the task. This is something you should avoid.

Categories

Resources