2

Basically I want get data I already have accessed from javascript and passing it to Java/Android so that I can work with it there.

     /* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface {


        @SuppressWarnings("unused")
        public void setX(String html){
            Activity.this.x = html;
            Toast.makeText(myApp, Activity.this.x, Toast.LENGTH_LONG).show();
        }

    }

this works but I want to be able to call the same Toast line anywhere and get the same result. Currently it only returns null/empty when not called through loading through webview.loadUrl("Javascript:"...

Any tips?

3 Answers 3

4

You can not access stored javascript variables, you must do it through a function call. You have to call it from javascript in your html page, for example:

TheNameOfYourInterface.setX('value');

TheNameOfYourInterface will be a javascript object when you add the interface to the webview via

YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),"TheNameOfYourInterface");

so you can do the logic on your webview and call the interface when you set the data so the method in the Java side will be called.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm kinda sad to say that you are right. This seems to be the only way to pass back any sort of JS information to the activity.
1

I found a different solution to what I need, and I feel like it works for all who do not need get a value calc'd by javascript. My solution to my need was to HTTP GET the html/javascript and then parse it as a string. It saves me some time by not needing to load X WebViews and then (re)creating all my functions in the JavaScript Interface.

Comments

0

I think it will be a good idea to store the HTML in Shared Preferences ,which is a form of persistent storage.This way you will be able to access it from anywhere.

   //------get sharedPreferences

SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);

//--------modify the value

pref.edit().putString("ToastString", html).commit();

//-------get a value from this from anywhere

String toastValue=pref.getString("ToastString", "");

1 Comment

I tried to implement this and it doesn't seem to work. There seem to be 2 seperate vars with the same name going on 1) in JavaScriptInterface that actually is set and the other in the main activity that stays null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.