Insert a java string into phonegap javascript

扶醉桌前 提交于 2019-12-12 03:49:06

问题


I am trying to insert a java string into phonegap javascript.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String myName = "Xxxxx";

    super.loadUrl("file:///android_asset/www/login.html");
}

I just want to insert myName string into login.html so that I can use the string from javascript. Any idea plz?

is there any simpler way except plugin, like localstorage or anything else?
If it is must to make a plugin, then what is the way to fetch this string from here into that plugin?

I am new in both phonegap and android. Plz help.


回答1:


Try to pass sting via querystring, like

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String myName = "Xxxxx";

    super.loadUrl("file:///android_asset/www/login.html?name=" + myName );
}

take a look here to use querystring on javascript




回答2:


In your MainActivity :

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  JavaScriptInterfaceClass myInterface = new JavaScriptInterfaceClass(this, appView);
  appView.addJavascriptInterface(myInterface, "Android");

  super.loadUrl("file:///android_asset/www/login.html");
}

Create a new class in your project for instantiating myInterface(works only for phonegap):

public class JavascriptInterfaceClass {
    private WebView mAppView;
    private DroidGap mGap;

public JavascriptInterfaceClass(DroidGap gap, WebView view) {
    mAppView = view;
    mGap = gap;
}

public String getMyString() {
  String myName = 'xxxxx';
  return myName;

}

In your WebView:

<script type="text/javascript">
  function getString() {
      return Android.getString();
  }
</script>


来源:https://stackoverflow.com/questions/15653441/insert-a-java-string-into-phonegap-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!