0

I'm new into Android development and stuck with this documentation and this tutorial

Basically, I want to print a web page into a PDF. But when using the documentation I'm getting error with getActivity() function.

And in the second link (the tutorial) I'm getting error with PlaceholderFragment().

Could anyone give me a complete example to print a HTML Page?

I also want to know what a fragment is? Should I create a fragment to make the code work? And how to do that?

1 Answers1

0

An Android App is structured to have many components: activities, fragments, services, adapters, models and your controller/business classes.

Each component extends a specific android class. For example, activities extends Activity class or AppCompatActivity class. Fragment can extend Fragment class, Service extends Service class, and so on...

There are some methods that can only be used in activity because they are Activity class methods (or ascendant).

So if you need to use the getActivity() method, that can be used by a Fragment, but you are not in a fragment, you need to get the activity in some other way.

For example:

private void doWebViewPrint() {
    WebView webView = new WebView(getActivity());
}

should become:

private void doWebViewPrint(Activity activity) {
    WebView webView = new WebView(activity);
}

and you have to call it from an activity calling:

webprinter.doWebViewPrint(this);

or even better:

private void doWebViewPrint(Context context) {
    WebView webView = new WebView(context);
}

and you have to call it from an activity calling:

webprinter.doWebViewPrint(getApplicationContext());

In the second link you wrote, I can't find any mention to PlaceholderFragment.

By the way, it is not mandatory to use fragments in your app, you can just use activities for having a working app. Fragments are useful for managing different "views" in a same container of an activities, for example when using a navigation drawer, they have their own lifecycle and can be attached and detached without changing activity.

You can find more information on how to Print HTML to PDF here.

Community
  • 1
  • 1
Jackie Degl'Innocenti
  • 1,251
  • 1
  • 14
  • 34