Add a java program to run within the Android Studio app - javascript

I am just a side programmer, working on little tiny projects for some extra coin. Nothing to big.
But I got this code with an if and else if statement that I am trying to run on the GUI on Android Studio, I want the code to display within the actual android app. I don't know where to put the code in or how to call it in the .java file, so that it can run in the android app on the Studio program. I was hoping maybe someone with more experience with Android Studio can help me figure out what my next steps are. I do apologize if I am vague with my problem, I am not quite great at explaining the issue.
public class Main {
public static void main(String[] args) {
String lit;
Scanner scan = new Scanner(System.in);
System.out.println("Set the thermostat to call for heating, does the pilot stay lit? y/n");
lit = scan.nextLine();
if (lit.equals("y")) {
System.out.println("Great. So it works.");
} else if (lit.equals("n")) {
System.out.println("Check the thermocouple.");
}
}
}

Android apps work in a different way to 'normal' java programs, the concept of System.in doesn't really exist. The main function isn't something that you call manually. User input comes from having widgets on the screen like an EditText to read the data.
I'd start here to get a grasp on a basic app and then you should be able to see how you could modify your sample above to an app.

I see you need to make an actual GUI app with this.
I would suggest you to see some tutorials on android studio first.
To build this app, first put in 2 Textview, and 2 buttons in the activity_main.
In the properties panel on the left, change the text of these objects so that your question is in one textView, the other is blank and the buttons are labelled Yes or No (or y and n, your choice).
Change the id of the 2 buttons so that one's id is yes and the other's is no. Set the id of the blank textView as result.
Now, in the main activity, put this in BEFORE #Override:
Button yes = (Button) findViewById(R.id.yes);
Button no = (Button) findViewById(R.id.no);
TextView result = (TextView) findViewById(R.id.result);
And put this AFTER setContentView (on the next line):
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText("Whatever your message is for yes");
}
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText("Whatever your message is for no");
}
I hope this is what you wanted. Once again, I would advise you to watch some tutorials.

Android Apps have no CUI console.
You must implement those outputs through Android's GUI APIs, for example, TextView, Toast or etc.

Related

Android WebView call JavaScript function

I using WebView to show this website
http://app.wlojii.com
I want to make control panel in notification bar to play/stop music.
The problem i cant find the function that play/stop the music.
I inspected the button element and tried some variants of functions unsuccessfully (play, play(), player.play()), and i used this method to call the functions:
mWebView.loadUrl("javascript: ...")
I am not so familiar with JavaScript and web, i need some help.
Pavel
I have added a git repo with the working code https://github.com/premithk/webviewclickeventexample
The problem last time was that getElementsByClassName returns an array. So i have changed the code to
mWebview.loadUrl("javascript(function({l=document.getElementsByClassName('mejs-playpause-button');
e=document.createEvent('HTMLEvents');
e.initEvent('click',true,true);
l[0].dispatchEvent(e);})()");
Any ways the code in repo works such that there is a button (native) that will act as play/pause
Register a Javascriptinterface or use this library.
https://github.com/lzyzsd/JsBridge/blob/master/README.md
The library acts as a bridge between webview and the Java part of the app
Yes, The idea is to inject an object to the JS part and use that as a bridge to call a function inside the native part. Have updated the git repo reflecting the change. Only thing is that before we inject the event listener we have to make sure the page is fully loaded, so it might take some time. So first thing is to add the interface mWebview.addJavascriptInterface(new JSInterface(), "jsnativebridge");
Then define the class
private class JSInterface {
#JavascriptInterface
public void playPauseClicked(String string) {
Log.d("console", "" + string);
}
}
Then wait for page load and add the event listener like below
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
public void onPageFinished(WebView view, String url) {
Log.d("console", "" + "loaded");
mWebview.loadUrl(
"javascript:(function() { " +
"var ch=document.getElementsByClassName('mejs-playpause-button');" +
"ch[0].addEventListener('click', function(){" +
" jsnativebridge.playPauseClicked('Yes');" +
"});"+
"})()"
);
}
});
You can refer the git repo, have added a working demo.
Cheers

Android: Pop-up alert while calculations are performed

I'm moving a pc java code to android by using Android Studio. The java code performs some numeric calculations routines and in a basic computer it can take few seconds to return the problem solution. The java code works very pretty.
By clicking in a button, the routine starts. I'd like to know how to show an elegant "alert" mensagem while the calculations are performed. A kind of "please wait" in a pop-up.
My basic code:
static double h,w,l,t,Te;
static int ambiente;
private EditText numeroin;
//private TextView numeroout;
public void cliqueBotao(View view){
Intent intent = getIntent();
ambiente = intent.getIntExtra("ambiente_selec", 0);
numeroin=(EditText)findViewById(R.id.in_h);
h= Double.parseDouble(numeroin.getText().toString());
numeroin=(EditText)findViewById(R.id.in_w);
w= Double.parseDouble(numeroin.getText().toString());
numeroin=(EditText)findViewById(R.id.in_l);
l= Double.parseDouble(numeroin.getText().toString());
numeroin=(EditText)findViewById(R.id.in_t);
t= Double.parseDouble(numeroin.getText().toString());
numeroin=(EditText)findViewById(R.id.in_T);
Te= Double.parseDouble(numeroin.getText().toString());
(HERE STARTS THE NUMERICAL CALCULATIONS CODE)
/**AlertDialog msg;
msg=new AlertDialog.Builder(this).create();
msg.setMessage("Calculando");
msg.show();*/
}
By the way, in the button xml code the OnClick option is seted to "cliqueBotao".
You should do that math in a worker thread, take a look at AsyncTask. You can use onProgressUpdate and onPostExecute callbacks to control your pop-up dialog lifecycle and even display current calculation progress.
As suggested by Rogério, AsyncTask was the best solution to my problem. On the other hand, I had to discover how to start a new activity by using AsyncTask. It was not easy for me, but a useful solution is here: Android AsyncTask: start new Activity in onPostExecute()

onPageFinished Javascript WebView

I feel pretty stupid for having to ask this but I can't for the life of me get it to work.
So I've searched around and found lots of help, guides, and etc for using the onPageFinished function in WebViewClient and my code is largely based on these.
Basically I have a function that is supposed to load a web page and then hides certain elements on that page with the onPageFinished. Instead of actually doing this though it hides the entire page and the webview displays the text "none".
When I comment out the onPageFinished function the webview loads the page just fine which leads me to believe that it has to be the javascript but according to the w3c site my javascript is correct for what I want to do...
So my question is this, Does anyone see the problem with the below code and/or anyone have a suggestion for something else that might accomplish my above stated goals?
Any help in getting this to work would be greatly appreciated.
Code:
public class MainActivity extends AppCompatActivity{
private WebView browser;
private String url = "https://www.google.com";
< onCreate calls cleanPage and other stuff >
public void cleanPage() {
browser = (WebView) findViewById(R.id.webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
browser.loadUrl("javascript:document.getElementById('lga').style.display='none';");
}
});
browser.loadUrl(url);
}
}
Notes:
-The above uses google as an example, lga is the id of the google banner div.
-browser and url are global because once I get cleanPage working I will add in other functions that will alter them as needed.
You need to add void(0); at the end of your javascript: URL. Otherwise, WebView replaces your current page with the result of the JS evaluation (in your case, that is the string "none").
So change this:
browser.loadUrl("javascript:document.getElementById('lga').style.display='none';");
to:
browser.loadUrl("javascript:document.getElementById('lga').style.display='none';void(0);");

How to debug the silk browser on the Kindle Fire?

I am experiencing some different javascript behavior when running my site on Kindle Fire than through Chrome. In order to debug this I need access to something like the Chrome Developer Tool or Firebug. Any suggestions?
In the same boat here... was hoping adb logcat would help, but javascript console messages don't seem to appear there. Perhaps there's something that needs to be set on the device to direct console logs to logcat?
edit: found a decent solution: http://jsconsole.com -- allows you to set up a remote debug/logging console. Pretty simple (console logging only, so you'll need to dump a lot of into into the logs)... but it works well. Helped me track down the source of my issues, at least!
how-to: http://jsconsole.com/remote-debugging.html
I took a different approach and created a wrapper native app that pop up a dialog for JavaScript.
My wrapper code is rather large, so I took a snippet of the relavant parts. It actually works and will display ANY javascript error.
// registers the debugger to catch errors
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.setWebChromeClient(new DebugClient(this));
// the class that manages the errors
private class DebugClient extends WebChromeClient {
Activity activity;
public DebugClient(Activity activity) {
this.activity = activity;
}
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
if (consoleMessage.messageLevel() == MessageLevel.ERROR
|| consoleMessage.messageLevel() == MessageLevel.WARNING) {
String title="Javascript error on line "
+ String.valueOf(consoleMessage.lineNumber())
+ " of " + consoleMessage.sourceId();
AlertBox alertBox=new AlertBox(activity, (ActionListener)null, title, consoleMessage.message(), "OK");
alertBox.show();
alertBoxes.add(alertBox);
}
return true;
}
}
To compile this, you'll need to install the Android SDK on your computer, and probably a Java IDE (Eclipse?) with ADT. Then you just do: create new project, add a WebView component into your layout/main.xml, and paste the code. Compile and install on your Kindle Fire.

Getting content out of WebView In a unit test Android, using java script

I have been able to get content out of WebView using javascript and loadUrl() method having specified an interface thats called from javascript string that is injected into WebView.The problem is that this only works for me when the loadUrl() method is present in onPageFinished() method in the WebView client. What I want to do is I want to get the content out of the WebView (with the content already loaded). The WebView is in an activity instrumentation test case and I can for instance use findAll() method and that works fine. For some reason I can not use loadUrl() and get the desired behaviour (which is injecting javascript and getting content out of the WebView with a help of an interface).
PLease help.
Thanks
Pawel
EDIT:
Just adding code to show what I am doing exactly:
Yes I understand that but my problem is that I am trying to do it within a test case this way:
public void testWebView() throws Exception {
solo.sleep(3000); // wait for views to load on the screen
WebView a=null;
ArrayList<View> views = solo.getCurrentViews(); // I am using solo object to get views for the screen currently loaded
for(View s:views)
{
if (s instanceof WebView)
{
a = (WebView)s; // this is where I get my WebView
}
}
Instrumentation inst = getInstrumentation();
inst.runOnMainSync(new Runnable()
{
public void run()
{
int d =a.findAll("something"); // this method runs fine on the object and i get the desired result
WebSettings settings = a.getSettings();
settings.setJavaScriptEnabled(true);
a.loadUrl("javascript:document.location = document.getElementById('google').getAttribute('href')"); // this javascript is never executed and that is my problem
}
});
}
You can inject javascript in a loaded page much the same way you can do it in desktop browsers - via inline javascript entered into navigation bar.
Bind some Java object so that it can be called from Javascript with WebView:
addJavascriptInterface(javaObjectExposed, "JSname")
Force execute javascript within an existing page by
WebView.loadUrl("javascript:window.JSname.passData("some data from page");");

Categories

Resources