7

I am getting an error "java.lang.IllegalStateException: Can print only from an activity" while using an android 4.4 printing API.

is it work on all android above 4.4?

my code

public class MainActivity extends Activity {

    Context cotext;
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cotext = getApplicationContext();
    }

    public void printData(View view){
        doWebViewPrint();
    }

    private void doWebViewPrint() {
        // Create a WebView object specifically for printing
        WebView webView = new WebView(cotext);
        webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("TAG", "page finished loading " + url);
                createWebPrintJob(view);
                mWebView = null;
            }
        });

        // Generate an HTML document on the fly:
        String htmlDocument = "<html><body><h1>Test Content</h1><p>Testing, " +
                "testing, testing...</p></body></html>";
        webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null);

        // Keep a reference to WebView object until you pass the PrintDocumentAdapter
        // to the PrintManager
        mWebView = webView;
    }

    private void createWebPrintJob(WebView webView) {

        // Get a PrintManager instance
        PrintManager printManager = (PrintManager) cotext
                .getSystemService(Context.PRINT_SERVICE);

        // Get a print adapter instance
        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();

        // Create a print job with name and adapter instance
        String jobName = getString(R.string.app_name) + " Document";
        printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());

        // Save the job object for later status checking
        //mPrintJobs.add(printJob);
    }
}

please help me.

is there any example of android wifi printing?

VIISHRUT MAVANII
  • 11,410
  • 7
  • 34
  • 49
Riyas PK
  • 3,147
  • 1
  • 23
  • 29
  • May be this would help. http://stackoverflow.com/questions/14097990/require-android-program-to-connect-to-a-wifi-printer-and-physically-print-conten – Dipali Shah Jun 02 '16 at 06:28
  • Thank you @Dipalishah . can i do with https://developer.android.com/training/printing/custom-docs.html – Riyas PK Jun 02 '16 at 06:32

3 Answers3

13

I know this is late answer.

You have to use YourCurrentActivity.this instead of getApplicationContext()

Because getApplicationContext() refers to an whole application context while YourCurrentActivity.this refers only current activity context.

Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
  • 1
    I had used this instead of ActivityName.this and it still gave the same issue why? this also refers to the ActivityName.this right? then why was this issue faced for me? – Prajwal Waingankar Apr 13 '20 at 13:11
  • @PrajwalW It depends from where you used this. If you are in the onClick event of any button and use this. The this refers to the button context. – Chirag Savsani Apr 13 '20 at 13:17
  • I had used this inside of the function where we are calling PrintManager instance. So when I mention this in a function does that means it points to that functions context? – Prajwal Waingankar Apr 13 '20 at 14:08
  • Probably Yes. May be it refers to function context. – Chirag Savsani Apr 13 '20 at 14:14
12

My application is using PDF printing using PrintManager. I got this issue after I implemented Multi-language support.

Android create a new context via createConfigurationContext(). This invalidates the reference being used by the PrintManager instance, causing the above IllegalStateException.

Solution

My solution is to store a reference of the original context passed by attachBaseContext() a member of my activity. Then retrieve PrintManager instance by calling getSystemService() on the original context reference instead of the inactive context reference.

private Context originalContext;

@Override
protected void attachBaseContext(Context newBase) {
    this.originalContext = newBase;

    super.attachBaseContext(LocaleHelper.onAttach(newBase,appLocale));
}

//  Starting printing (PDF generation):

PrintManager printManager = (PrintManager) originalContext.getSystemService(Context.PRINT_SERVICE);
VIISHRUT MAVANII
  • 11,410
  • 7
  • 34
  • 49
  • 1
    Same here. I was giving an option to change language in my app. Then this problem occured. This answer solved my problem. Thanks! :) – Mohit Atray Jan 02 '21 at 18:19
1

If you're printing HTML content, this Android training is faster and easier.

Now for the exception, I think you are getting this exception because of this line:

PrintManager printManager = (PrintManager) cotext
            .getSystemService(Context.PRINT_SERVICE);

The context you're using is an application context although you're in an activity and can/should just use the activity as a context. I'm not sure why you would need a separate cotext at all in this code.

Nonos
  • 2,450
  • 2
  • 23
  • 34