0

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.

Mehdi
  • 540
  • 1
  • 11
  • 28

2 Answers2

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

Community
  • 1
  • 1
hkutluay
  • 6,794
  • 2
  • 33
  • 53
  • Hi hkutluay, thanks for the suggestion. It works for me. Actually....just what I want... Thanks again. – Mehdi Mar 27 '13 at 11:30
1

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>
Joe Lewis
  • 1,970
  • 2
  • 18
  • 20
  • Thanks a lot for ur help. (1) But it is showing error: Unable to start activity ComponentInfo{com.minfb/com.minfb.PhoneGapActivity}: java.lang.NullPointerException. (2) Another thing...`return Android.getString` or `return Android.getMyString`? any direction? – Mehdi Mar 27 '13 at 09:38
  • I hope the first answer did the trick in much simpler way. I haven't tried it before and thats why I answered with this one. Have no idea why it raises nullPointerException. I might use some more log information. and yes it's Android.getMyString() ! – Joe Lewis Mar 27 '13 at 11:42
  • Yes, first one is very simple to implement. I have learned about java constructors by your answer. Thanks a lot. – Mehdi Mar 27 '13 at 12:35