0

in this code Android app opens a web page with WebView and extracts a text from HTML which is between tags "body" and "/body".

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;

public class MainAc extends Activity {

    /** Called when the activity is first created. */
    @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView webView = (WebView) findViewById(R.id.web);
        TextView text2 = (TextView) findViewById(R.id.text);

        Button infoButton = (Button) findViewById(R.id.b1);
        infoButton.setOnClickListener(new OnClickListener(){
            public void onClick(View view){
                // here is your button click logic, for example running another activity (page)
                startActivity(new Intent(MainAc.this, JavaInterface.class));
            }   
        });







        class Javasc { 
            private TextView t2;       

            public Javasc (TextView i)   
            {
                t2 = i;
            }

            @SuppressWarnings("unused") 

            public void processContent(String ii) 
            { 
                final String content = ii;
                t2.post(new Runnable() 
                {    
                    public void run() 
                    {          
                        t2.setText(content);        
                    }     
                });
            } 
        } 


        webView.getSettings().setJavaScriptEnabled(true); 
        webView.addJavascriptInterface(new Javasc(text2), "INTERFACE"); 
        webView.setWebViewClient(new WebViewClient() { 
            @Override 
            public void onPageFinished(WebView view, String url) 
            { 
                view.loadUrl("javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText);"); 

            } 
        }); 

        webView.loadUrl("http://www.nytimes.com/2014/08/03/sports/basketball/pacers-paul-george-has-surgery-after-badly-injuring-leg.html?ref=sports");
    }

    }

Is it possible to use JavaScript functions for extracted text in android's TextView ?

for example this JavaScript function (or it could be any other JS function where need to work with text)

function myFunction() {
var text = document.body.innerText;
var titles =text.match(/^\n(.+?)\n\n/mg);
 for (var i = 0; i < titles.length; i++) {
   document.write(titles[i] + "<br />" + "<br />");
   }
   }

Thanks for answers :)

  • 2
    *Algorithms* are largely language-independent. What you're really asking is whether you can use JavaScript code in your Android app, not the algorithm. – T.J. Crowder Aug 18 '14 at 21:02
  • Outside of using a WebView I don't think you can directly work with JavaScript in Android. – zgc7009 Aug 18 '14 at 21:05
  • possible duplicate of [Android Calling JavaScript functions in WebView](http://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview) – Sam Dozor Aug 18 '14 at 21:10

3 Answers3

1

According to this article, the Dalvik VM supports Java's scripting features (javax.script). One of the premier languages supported by the javax.script stuff is, unsurprisingly, JavaScript.

So in theory, you can use the javax.script stuff to execute JavaScript code and get back results. I think (also based on that article), that you have to include the relevant jar(s) (javax.script isn't in the Android SDK). Fortunately, though, javax.script is largely a set of interfaces, which are implemented by jars for specific scripting languages.

Some resources about using javax.script to run script code:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    I will have to look into this when I get some time, if this works it is awesome... really didn't know Dalvik had any sort of support for this. – zgc7009 Aug 18 '14 at 21:10
0

You can use Rhino to achieve this. See specifically Context.jsToJava.

https://vec.io/posts/embed-javascript-in-android-java-code-with-rhino

jackb
  • 14,241
  • 3
  • 17
  • 7
-1

You want to do a regex on a text and resorting to javascript for it, which is unnecessary when you have a better faster API in java with no overhead.

The equivalent to your example is:

http://developer.android.com/reference/java/util/regex/Pattern.html

Pattern p = Pattern.compile("/^\n(.+?)\n\n/mg");
 Matcher m = p.matcher(myTextView.getText());
 while (m.find()) {
     String titles = m.group(1);
     Log.V("TAG", titles);
 }

There are plenty of other text analysis solutions included in the core framework or external libraries that have been proved for both mobile and server. You just have to look it up and not resort to a worse API you're comfortable with.

MLProgrammer-CiM
  • 17,231
  • 5
  • 42
  • 75
  • Downvote? Care to explain? He wants to do a regex on a text and hes resorting to javascript for it, which is unnecessary when you have a better faster API in java with no overhead. – MLProgrammer-CiM Aug 18 '14 at 21:08
  • 2
    I didn't downvote and honestly wouldn't, but the reason for the downvotes are likely that you aren't specifically answering the question nor are your providing an explanation as to how your code could solve the problem at hand in a more efficient way. You are leaving it up to future users (and this OP) to understand how your code solves the problem even if they don't have a good understanding of what you are doing. – zgc7009 Aug 18 '14 at 21:11
  • I believe that an answer to "I want to do something terribly terribly wrong" is not to encourage it but rather provide alternate better solutions. – MLProgrammer-CiM Aug 18 '14 at 21:12
  • 1
    You need to provide what your code is doing and why it is a better solution. Being asked "How do you build a car," and replying "You buy one," provides a means to more efficiently achieve similar results, but it doesn't directly answer the question or provide a reason that your solution is a better method. – zgc7009 Aug 18 '14 at 21:14
  • @MLProgrammer-CiM you can't possibly know what their full use-case is such that you can sit on-high and call his approach "wrong". Off the top of my head I can think of maybe 100 fantastic reasons you'd want to leverage Javascript in an Android app. – Sam Dozor Aug 18 '14 at 21:15
  • "Is it possible to use JavaScript functions for extracted text in android's TextView?" can you provide one of those reasons that's not available in the SDK or libraries and the overhead of bringing a javascript engine is justified? – MLProgrammer-CiM Aug 18 '14 at 21:17
  • @MLProgrammer-CiM how about ability to adjust your javascript server-side. Heck, if your codebase and/or expertise is in Javascript, to me that's justification enough. Not to mention, for Android 4.4 which uses Chrome for WebViews, you'd be leveraging V8's extremely fast regexp engine, which puts Android's Java implementation to shame! – Sam Dozor Aug 18 '14 at 21:30
  • I'd like to see those regexp numbers. And writing for a single Android version is far from recommendable, and making apps in Javascript has been leveraged as bad by a large portion of the sector after huge failures like Facebook's Phonegapp App. I can understand the blind love for javascript by web developers but pretending is the one-size-fits-all, even as a scripting engine, seems quite far fetched. – MLProgrammer-CiM Aug 18 '14 at 21:35
  • http://benchmarksgame.alioth.debian.org/u64/javascript.php regex are faster by a factor of 1/7, colour me surprised. I still wouldn't leverage the overhead of loading the webview vs going JNI/NDK. – MLProgrammer-CiM Aug 18 '14 at 21:39
  • I thought it will be easier.. maybe this can be done with the PHP (JavaScript functions rewrite in PHP) -> JSON -> Android ? Sorry if my ideas are awful, I'm still beginner in programming. – Rafaelo PA Tarmazam Aug 18 '14 at 21:40
  • there you have it - the link you posted clearly shows regexp's superiority. Will be my last post as this isn't the right forum. Also, I'm a java guy - I hate Javascript. I just thought your original answer was horrible, as @zgc7009 eluded to. – Sam Dozor Aug 18 '14 at 21:43
  • @SamDozor Glad to continue this discussion somewhere else. – MLProgrammer-CiM Aug 18 '14 at 21:45