Access to WebView from another function in MainActivity class Access to WebView from another function in MainActivity class android android

Access to WebView from another function in MainActivity class


You're trying to use view before it has been initialized. You need to wait until after view = (WebView) findViewById(R.id.webView); has been called in order to initialize onServerReceive.

EDIT: Looking at this some more what's more likely happening is that you're using your instance of onServerRecieve before view is initialized in onCreate().

@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    ...    view = (WebView) findViewById(R.id.webView);    onServerRecieve = createListener()    view.getSettings().setJavaScriptEnabled(true);    ...    view.loadUrl("file:///android_asset/loading.html");}...@JavascriptInterfacepublic void websocket_start(){    try {        mSocket = IO.socket("http://some web com:8888");        mSocket.on("connect", onConnect);        mSocket.on("server_receive", onServerReceive);        mSocket.connect();    } catch (URISyntaxException e) {}}private Emitter.Listener createListener() {    return new Emitter.Listener() {    @Override    public void call(final Object... args) {        runOnUiThread(new Runnable() {            @Override            public void run() {                final String argsStr = TextUtils.join(",", args);                view.loadUrl("javascript:receive('" + argsStr + "')");            }        });    }};}public Emitter.Listener onServerReceive;}


Finally found the answer and the problem

I had this

view.addJavascriptInterface(new MainActivity(), "access_android");

and in web js I accessed android with this "access_android.websocket_emit()"

and i think because of "new MainActivity()" it was creating a new class where "view" wasn't defined. so I replaced "new MainActivity()" with "this"

view.addJavascriptInterface(this, "access_android");

now all works fine ! thanks good bye