Add 1 - Javascript Android Studio - javascript

Trying to make a "click counter" game in android studio.
int clicked = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.counter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked++;
text.setText(clicked);
}
});
}
This is the code i set up for the counter. Any ideas about what i might be doing wrong?

Try: #Override public void onClick(View v) { clicked+=1; text.setText(String.valueOf(clicked);
text.invalidate();}

Related

How to listen the page beforeunload or unload event in android webview by JavaScript

I use a WebView to load my page below:
<html>
<head>
</head>
<body>
<h1>first page</h1>
<script>
(function(){
function log(e){
console.log("Page is going to unload:"+e);
}
window.addEventListener('beforeunload',log);
window.addEventListener('unload',log);
})()
</script>
</body>
</html>
this page has worked well in Chrome or other PC-browser。
Here is the code in activity:
public class MainActivity extends AppCompatActivity {
WebView web;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = findViewById(R.id.web);
web.setWebContentsDebuggingEnabled(true);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
web.loadUrl("http://192.168.0.103:5000/WebContent/");
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
Log.i("SSSS","acitvity destroyed");
super.onDestroy();
ConstraintLayout layout = this.findViewById(R.id.rootView);
layout.removeView(web);
web.destroy();
web = null;
}
}
when leave the activity that contains WebView ,I cannot catch any logs about page unload event,is anything wrong?
I didn't test this but based on the documentation you need to override WebChromeClient::onConsoleMessage and use WebView::setWebChromeClient.
This is because you are removing view and Webview in onDestroy
#Override
protected void onDestroy() {
Log.i("SSSS","acitvity destroyed");
super.onDestroy();
ConstraintLayout layout = this.findViewById(R.id.rootView);
layout.removeView(web); <----- This linse
web.destroy(); <------ Forcing webview to destroy and next explicitly set null
web = null;
}

Two onClick actions one button at same time

I am developing a program in android studio. I want when I click a button then action will perform at the same time.
Function:
1st - Start count clicks
2nd - after 5 seconds that button disable
setDelay = new Handler();
btn = (Button) findViewById(R.id.bt);
final Button disableMe = (Button) findViewById(R.id.bt);
final TextView text = (TextView) findViewById(R.id.timeUp);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startDelay = new Runnable(){
#Override
public void run(){
text.setText("Time Up!");
disableMe.setEnabled(false);
}
};
setDelay.postDelayed(startDelay, 5000);
}
});
txv = (TextView) findViewById(R.id.tx);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCounter ++;
txv.setText(Integer.toString(mCounter));
}
});
This can help
private int clicks = 0;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final Button b = (Button)v;
if (clicks == 0){
// Means its the first time that a user click the button
// Start a thread that is going to disable the button after 5 seconds from first click
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
b.setText("Time up");
b.setEnabled(false);
// Showing user clicks after button is disabled
showClicks();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// Here we are just counting . . . . including the first click
countClicks();
}
});
Count clicks method
private void countClicks(){
++clicks;
// You can update your text view here
}
Showing total clicks
private void showClicks(){
Toast.makeText(this, Integer.toString(clicks), Toast.LENGTH_SHORT).show();
}
Just use a boolean variable to tell if the disable Runnable is started:
button.setOnClickListener(new View.OnClickListener() {
boolean disableRunnableStarted = false;
Runnable disableRunnable = new Runnable(){
#Override
public void run(){
//Running on UI thread to update button
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
button.setEnabled(false);
}
});
}
};
#Override
public void onClick(View v) {
if(!disableRunnableStarted) {
Log.d(TAG,"Starting disable runnable and incrementing counter...");
new Handler().postDelayed(disableRunnable,5000);
disableRunnableStarted = true;
//Here increment your counter
} else {
Log.d(TAG,"Just incrementing counter...");
//Here increment your counter
}
}
});
Replace MainActivity with your Activity's name, if executing in a Fragment replace by getActivity().
create new list like this :
ArrayList <View.OnClickListener> clickList = new ArrayList<>();
then add all your Listener :
final Runnable startDelay;
clickList.add(new View.OnClickListener(){
#Override
public void onClick(View v){
if (startDelay != null)
return;
startDelay = new Runnable(){
#Override
public void run(){
text.setText("Time Up!");
disableMe.setEnabled(false);
}
};
setDelay.postDelayed(startDelay, 5000);
}
});
clickList.add(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCounter ++;
txv.setText(Integer.toString(mCounter));
}
});
then , in your button add this Listener:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (View.OnClickListener c : clickList)
c.onClick(view);
}
});

Toggle button doesn't work at the first time on Android

I wrote an Android app with toggle button but toggle button does not work well at the first time. But after unchecking, if you try again, it is working properly after that.
I listed below my codes.
Which codes I have to add to activate it for the first time?
public class MainActivity extends Activity{
private ToggleButton togg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togg = (ToggleButton) findViewById(R.id.toggleButton1);
}
public void nameOfMethod(View v){
togg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (togg.isChecked()) {
//Toast.makeText(MainActivity.this, "Servise bağlanılıyor...", Toast.LENGTH_SHORT).show();
new Thread(new ClientThread()).start();
} else {
Toast.makeText(MainActivity.this, "Bağlantı sonlandırılıyor...", Toast.LENGTH_SHORT).show();
}
}
});
}
in .xml file:
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="nameOfMethod"
android:textOn="Bağlantıyı bitir"
android:textOff="Bağlantıyı başlat" />
EDIT: It works just fine like that:
public class MainActivity extends Activity{
private ToggleButton togg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togg = (ToggleButton) findViewById(R.id.toggleButton1);
togg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (togg.isChecked()) {
//Toast.makeText(MainActivity.this, "Servise bağlanılıyor...", Toast.LENGTH_SHORT).show();
new Thread(new ClientThread()).start();
} else {
Toast.makeText(MainActivity.this, "Bağlantı sonlandırılıyor...", Toast.LENGTH_SHORT).show();
}
}
});
}
with moving setOnClickListener method to onCreate(Bundle savedInstanceState) and deleting android:OnClick method in .xml file...
You should set checked status for the toggle button in xml or in your code.
Xml
android:checked="true"
Or code:
togg = (ToggleButton) findViewById(R.id.toggleButton1);
togg.setChecked(true);
Otherwise, you can use
togg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO
}
});
instead of OnClickListener().
It will be ok if you still want to use OnClickListener, but remember to put it it onCreate instead of putting it in nameOfMethod. (Or remember call nameOfMethod in onCreate)
To put it onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togg = (ToggleButton) findViewById(R.id.toggleButton1);
togg.setChecked(false);
togg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
});
}
Well it appears that you're setting your click listener AFTER the toggle button is selected the first time, which explains the behavior you're getting.
Move the code to set your listener outside of nameOfMethod() and it should work.
EDIT: Sorry If I wasn't clear, just remove the setOnClickListener method from your nameOfMethod(). nameOfMethod() is what will be called each time the toggle button is selected, so it really makes no sense to set a listener each time it's touched..that is why you're getting such unusual behavior.
Instead, in your nameOfMethod(), just go right ahead and set up your conditions based on the state of the toggleButton
if(toggleButton.isSelected()){
..........
{
else
.......

programmatic click in Android WebView

I have a website with href in it which redirected me to https
<a id="mA" href="javascript:pLogin(2)" class="login-link__link private-cab-link"><i class="icon-user"></i>Авторизация</a>
So, I can click on it by JavaScript. It works in chrome console
javascript:(function(){document.getElementById('mA').click();})()
Now I'm trying to do the same in WebView by clicking my app's button.
public class RostelecomLoginActivity extends Activity {
WebView webView;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_rostelecom_login);
Intent webIntent = getIntent();
String url = webIntent.getStringExtra("url");
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setSavePassword(true);
webView.loadUrl(url);
Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});
}
}
I'm using MyWebViewClient to allow all certificates
public class MeWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
}
The js injection doesn't work. If I click on href in WebView it works.
What can be wrong?
click() isn't implemented in android js interface, you have to use HTML DOM Event Object, like this:
webView.loadUrl("javascript:(function(){"+
"l=document.getElementById('mA');"+
"e=document.createEvent('HTMLEvents');"+
"e.initEvent('click',true,true);"+
"l.dispatchEvent(e);"+
"})()");
You'll have to add a javaScript interface to the WebView to call a JavaScript function from android code.
Try something like this:-
Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JavascriptInterface javasriptInterface = new JavascriptInterface(RostelecomLoginActivity.this);
webView.addJavascriptInterface(javasriptInterface, "MyInterface");
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});

Search & Highlight a word from html webpage shown in webview?

I want to search and highlight a word in android webview, I tried with this code but it is not working. My code is here:
webview.findAll("a");
webview.setSelected(true);
webview.findNext(true);
try {
for (Method m : WebView.class.getDeclaredMethods()) {
if (m.getName().equals("setFindIsUp")) {
// m.setAccessible(true);
m.invoke(webview, true);
break;
}
}
} catch (Exception ignored)
{
Log.i("highlight error", ignored.toString());
}
This code is not setting any highlight on the selected word or not giving any error so please tell me how to search for and select a word in a webview ,currently i am trying for android version 3.2?
Setup a search button on your WebView layout.
Set up the WebView, and then a Search Button as follows. The popup dialog has a Cancel Button, a Search Button and an Edit Text for the search term. When search is pressed, each match of the EditText string will be highlighted in the WebView.
final Activity activity = this;
webView = (WebView) findViewById(R.id.yourWebView);
webView.setScrollbarFadingEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.clearCache(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setTitle("Loading Web Page");
progressDialog.setIcon(R.drawable.ic_menu_allfriends);
progressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
webView.destroy();
finish();
} });
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if(progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
webView.loadUrl(yourStringURL);
Button search = (Button) findViewById(R.id.butSearch);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//set up button for search keyword of the webView
final Dialog dSearch = new Dialog(myActivity.this);
dSearch.setContentView(R.layout.search_keyword);
dSearch.setCancelable(true);
dSearch.setTitle(getString(R.string.yourTitle));
Button cancel = (Button) dSearch.findViewById(R.id.searchCancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dSearch.dismiss();
}
});
Button search = (Button) dSearch.findViewById(R.id.searchAdd);
search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText etkw = (EditText) dSearch.findViewById(R.id.searchword);
String keyword = etkw.getText().toString();
dSearch.dismiss();
webView.findAll(keyword);
try
{
Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
m.invoke(webView, true);
}
catch (Throwable ignored){}
}
});
dSearch.show();
}
});

Categories

Resources