Mixed JSON's Android Android application

Through the WebView to call java method in the javascript code, javascript code java code execution, data exchange between the two by json

Set the WebView widget

// connect to our browser so we can manipulate it
browser = (WebView) findViewById(R.id.calculator);

// set a webview client to override the default functionality
browser.setWebViewClient(new wvClient());

// get settings so we can config our WebView instance
WebSettings settings = browser.getSettings();

// JavaScript?  Of course!
settings.setJavaScriptEnabled(true);

// clear cache
browser.clearCache(true);

// this is necessary for "alert()" to work
browser.setWebChromeClient(new WebChromeClient());

// add our custom functionality to the javascript environment
browser.addJavascriptInterface(new CalculatorHandler(), "calc");

// uncomment this if you want to use the webview as an invisible calculator!
//browser.setVisibility(View.INVISIBLE);

// load a page to get things started
browser.loadUrl("file:///android_asset/index.html");

// allows the control to receive focus
// on some versions of Android the webview doesn't handle input focus properly
// this seems to make things work with Android 2.1, but not 2.2
// browser.requestFocusFromTouch();



Activity will be a range variable named browser's tied to the WebView control. WebView is a very complex class, highly customizable. For example, you need to set number of classes to be associated with the web browser is expected to function. This is the programmer must invest some effort to get some useful function in the world. However, this custom is no limit. For purposes of this application, WebView control has been minimal deployment.

WebViewClient provide hooks to capture a variety of events, these events include the beginning and end of the page is loaded, the form re-submitted, keyboard tracking and interception, and manipulation of programmers like many other events. Similarly, you need WebChromeClient an example of very useful for allowing such as alert () JavaScript function like function. WebSettings to enable the control using JavaScript.

JavaScript Interface Connection

Activity in the next step is to enable Java code to HTML files with WebView management interaction in the JavaScript code. This is done by calling addJavascriptInterface () method to complete, as shown in Listing 4.

The function of the parameter is a Java class instance and a name space identifier. For example, for this application, you define a calc name space, and achieving a class called CalculatorHandler the code shown in Listing 5.

Listing 5. CalculatorHandler achieve
// Javascript handler
final class CalculatorHandler
{
    private int iterations = 0;
    // write to LogCat (Info)
    public void Info(String str) {
        iterations++;
        Log.i("Calc",str);
    }
    // write to LogCat (Error)
    public void Error(String str) {
        iterations++;
        Log.e("Calc",str);
    }
    // sample to retrieve a custom - written function with the details provided
    // by the Android native application code
    public String GetSomeFunction()
    {
        iterations++;
        return "var q = 6;function dynamicFunc(v) { return v + q; }";
    }
    // Kill the app
    public void EndApp() {
        iterations++;
        finish();
    }
    public void setAnswer(String a)
    {
        iterations++;
        Log.i(tag,"Answer [" + a + "]");
    }
    public int getIterations()
    {
        return iterations;
    }
    public void SendHistory(String s)
    {
        Log.i("Calc","SendHistory" + s);
        try {
            JSONArray ja = new JSONArray(s);
            for (int i=0;i<ja.length();i++) {
                Log.i("Calc","History entry #" + (i+1) + " is [" + ja.getString(i)+ "]");
            }
        } catch (Exception ee) {
            Log.e("Calc",ee.getMessage());
        }
    }
}

In the JavaScript environment, access CalculatorHandler by window.calc.methodname grammar approach. For example, CalculatorHandler implement a called Info () method, which accepts a string parameter and the write in the Application log. Access this method from the JavaScript environment, you can use syntax like this: window.calc.Info ("write this string to the application log !");。

Basic understanding of how to call Java code from JavaScript code, we will look at the index.html file in Listing 6 to see how the various methods being called.

Listing 6. WebView control is rendered (and executed) index.html
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=0.25,
    user-scalable=yes" />
<title>Android to JavaScript with JSON</title>
</head>
<script language="JavaScript">
var cmdHistory = new Array();
function startup() {
    try {
        window.calc.Info("Starting up....");
        cmdHistory[cmdHistory.length] = "startup";
    } catch (ee) {

    }
}
function PerformSimpleCalculation(formula) {
    try {
        cmdHistory[cmdHistory.length] = "PerformSimpleCalculation";
        var answer = eval(String(formula));
        document.getElementById('data').value = answer;
        window.calc.setAnswer(answer);
    }    catch (ee)     {
        window.calc.Error(ee);
    }
}
function PerformComplexCalculation(andmethod) {
    try    {
        /*
         * argument to this function is a single object with 2 "members or properties"
         * operation: this is a string naming what we want the function to do.
         * array of arguments: this is an array of integers
         *
         */
        //alert(andmethod.operation);
        //alert(andmethod.arguments.length);
        if (andmethod.operation == "addarray") {
            cmdHistory[cmdHistory.length] = "PerformCompleCalculation-addarray";
            var i;
            var result = 0;
            for (i=0;i<andmethod.arguments.length;i++) {
                result += andmethod.arguments[i];
            }
            document.getElementById('data').value = result;
            window.calc.setAnswer(result);
        }
        if (andmethod.operation == "multarray") {
            cmdHistory[cmdHistory.length] = "PerformCompleCalculation-multarray";
            var i;
            var result = 1;
            for (i=0;i<andmethod.arguments.length;i++) {
                result *= andmethod.arguments[i];
            }
            document.getElementById('data').value = result;
            window.calc.setAnswer(result);
        }
    }    catch (ee)    {
        window.calc.Error(ee);
    }
}
function dynamicfunction()
{
    try {
        cmdHistory[cmdHistory.length] = "PerformCompleCalculation-dynamic";
        eval(String(window.calc.GetSomeFunction()));
        var result = dynamicFunc(parseInt(document.getElementById('data').value));
        document.getElementById('data').value = result;
    }catch (ee) {
        alert(ee);
    }
}
</script>
<body >
<center>
<h3>Running in Web View :)</h3>
this is some sample text here <br />
<input type="text" value="starting value"><br />
<button>Log
 Info</button>&nbsp;&nbsp;
<button>Log
 Error</button><br />
<button>Dynamic</button>
<button>How
    Many Calls</button>
<button>
    History</button>
<button>Kill This
 App</button><br />
</center>
</body>
</html>


Closer look at the list at the end of the button handler 6. Basically, these are called window.calc button handler method name space, these methods AndroidJSON.java the CalculatorHandler class implementation.

Listings 5 and 6 work together to demonstrate the JavaScript environment and the Java source file initialization code to achieve interaction. But how to initialize the code from the Activity you want to occur in the WebView step?

Should now be more in-depth look at Java code.

Insert JavaScript code

From a mathematical formula is passed to the JavaScript code to calculate the beginning of such a task. JavaScript's greatest (and most dangerous) is one of the characteristics eval () function. eval () function allows a string of code run time. In this case, you received from the EditText control is a string and passed to the JavaScript environment calculations. Specifically, we call in Listing 6 PerformSimpleCalculation () function.

AndroidJSON.java Listing 7 contains the code that handles button to select.

Listing 7. From Java called PerformSimpleCalculation () JavaScript function

  btnSimple.setOnClickListener(new OnClickListener()
  {
       public void onClick(View v) {
         Log.i(tag,"onClick Simple");
         // Perform action on click
         try
         {
            String formulaText =  formula.getText().toString();
            Log.i(tag,"Formula is [" + formulaText + "]" );
            browser.loadUrl("javascript:PerformSimpleCalculation(" + formulaText + ");");
         }
         catch (Exception e)
         {
               Log.e(tag,"Error ..." + e.getMessage());
         }
       }
  });


No matter how many rows this way, where the only concern is browser.loadurl () line, which passes a format string: javascript: <code to execute>.

This JavaScript code is injected into the WebView's current page and execute. So, Java code can execute JavaScript code defined in the WebView was.

In the Simple example, passed a string. However, when the need to address the more complex the structure of how to do it? This is where JSON can come in handy. Listing 8 shows PerformComplexCalculation () function call, the function see Listing 6.

Listing 8. By passing a JSON object to call a more complex function
btnComplex.setOnClickListener(new OnClickListener()
{
     public void onClick(View v) {
         Log.i(tag,"onClick Complex");
         // Perform action on click
         try
         {
             String jsonText = "";

             if (flipflop == 0)
             {
                 jsonText = "{ \"operation\" : \"addarray\",\"arguments\" : [1,2,3,4,5,6,7,8,9,10]}";
                 flipflop = 1;
             } else {
                 jsonText = "{ \"operation\" : \"multarray\",\"arguments\" : [1,2,3,4,5,6,7,8,9,10]}";
                 flipflop = 0;
             }
             Log.i(tag,"jsonText is [" + jsonText + "]" );
             browser.loadUrl("javascript:PerformComplexCalculation(" + jsonText + ");");
         }
         catch (Exception e)
         {
             Log.e(tag,"Error ..." + e.getMessage());
         }

     }
});


Look at the JavaScript function in Listing 6 PerformComplexCalculation. Note that the parameter is not passed in a string, but an object that you create yourself.

* Operation - to deal with the name of the function or procedure
* Arguments - this is a integer array

Object contains only two properties, but can be more complex to meet the higher demand. In this case, PerformComplexCalculation () JavaScript function supports two different operations: addarray and multarray. When these operations in the call to complete its work by calling the function window.calc.setAnswer, the result is passed back to Java code. Here, you see the Java and JavaScript code, two-way data flow.

In this case, you pass a JSON object, but get an experience in dealing with returns from the Java code to the Java string, it helps to convert them into a JavaScript string. This can be the same as in this case the value passed to the String by function to do: eval (String (formula));.

JavaScript eval () function uses the JavaScript string. Without conversion, then, eval function is not used for anything.

For a slightly more complex example, to encourage Hello nice about Dynamic button is selected in the WebView in the code.

To complete code example, look at an array of strings passed to the Java environment from the JavaScript environment.

JSON object exchange

Sample application (index.html) in the JavaScript code to a local function call record level page named cmdHistory array. Each time the function is called, you will add a new entry to the array. For example, when dynamicfunction () is called, a new string is stored: cmdHistory [cmdHistory.length] = "PerformCompleCalculation-dynamic";.

On this method, no particular place; it is just a collection of use data in the page-level example. Perhaps the data is stored in the database Android applications will be useful. How this data back to Java code?

To send a string to an array of objects, you call JSON.stringify function, the array is passed as a parameter. Necessary, stringify function allows customization of a complex object to be formatted a specific property. How is this done on more information, see the explanation json.org
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Mixed JSON's Android Android application

  • DWR brief introduction (to)

    DWR (Direct Web Remoting) is a Open source The class library that can help developers site contains AJAX technology. It can permit in the browser's code uses WEB server running on the JAVA function, just like it at the same browser. It contains t ...

  • DWR trial

    1, call not return value and parameters JAVA Ways 1.1, dwr.xml configuration <dwr> <allow> <create creator="new" javascript="testClass"> <param name="class" value="com.dwr.TestClass" /> ...

  • prototype, jQuery, Mootools, ext, dojo speed comparison

    Web20 are the cornerstone of AJAX, and now several online popular open source AJAX frameworks, such as: jQuery, Mootools, Dojo, Ext JS and so on, then we in the end of the circumstances under which the use of that framework? Following excerpt is a set of

  • js Simplified Traditional conversion code

    js Traditional Traditional Traditional Traditional javascript code conversion conversion code Reprint Address: http://www.cnblogs.com/genson/archive/2008/04/16/1004632.html js Simplified, Traditional conversion, IE7 through, Firefox does not pass, the pos

  • yiwei project management and maintenance of Javascript

    Namespace (namespace): A headache for the developers is the question how to prevent function name / class name and other people's conflicts, in an internal project team can be named among the scheduled (such as additional prefix, etc.) to solve t ...

  • Javascript in the browser environment (vi) incident

    Matter Examples of a lot of events. Such as user input, the click of a button and so on. Can put a javascript function assigned to an event (this can be called the event listener or event handler), when the incident happened, and will perform this functio

  • Wait for prompt js General category

    This is a very easy-to-use widget, the parameters have default values, default values, see the Notes wait = new WaitingTip(); wait.show(document.getElementById('id')); //Parameter 1 is displayed, in reference to the object ... wait.hide(); //Hide The use

  • JUnit Unit Testing Summary

    Read some of the unit test article, from the article in the interception of a number of information, which could be considered in the learning process, a summary of it! See future! Unit testing code is not used to prove you are right, but in order to ...

  • Hibernate Inteceptor

    The end of the project stage, the client suddenly put forward a very troublesome but normal demand, the system records all changes must be carried out. Formats such as: 2004.1.1 12:30 Ikuya wind orders Sales Order Date 2004.1.2-> 2004.1.3 The firs ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries