Load WebView with Embedded HTML code - Android - javascript

Below I attached the code to be executed with webview.
NOTE: JAVASCRIPT SHOULD BE ENABLED
ANYONE HELP ME TO RUN THIS HTML STRING IN WEBVIEW
<!DOCTYPE html>
<html>
<body>
<!-- Markup for HTML (Factors in Placement and Enrollment of Primary
Care Patientsin YMCA's Diabetes Prevention Program, Bronx, New
York,2010-2015) --><div class='rid_08184eef_309335'
data-apiroot='//tools.cdc.gov/api' data-mediatype='html'
data-mediaid='309335' data-stripscripts='true' data-stripanchors='false'
data-stripimages='false' data-stripcomments='true'
data-stripstyles='true' data-cssclasses='syndicate' data-ids=''
data-xpath='' data-oe='utf-8' data-of='xhtml' data-ns='cdc'
data-postprocess='' data-nw='true' data-iframe='true'
data-cdc-widget='syndicationIframe'
data-apiembedsrc='skins/larry//tools.cdc.gov/api/embed/html/js/embed-2.0.3.js'
data-iframeembedsrc='skins/larry//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js'></div><script
src='skins/larry//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js'
></script><noscript>You need javascript enabled to view this content or go to <a href='skins/larry//tools.cdc.gov/api/v2/resources/media/309335/noscript'>source URL</a>.</noscript>
</body>
</html>
I followed this link for basic setup. Nothing helped
BELOW I ATTACHED MY JAVA CODE
public class WebtestActivity extends Activity {
WebView webtest;
final Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.webviewtesting);
webtest=(WebView)findViewById(R.id.webtest);
String htmlString = "<!-- Markup for HTML (How to Prevent Cancer or Find It Early) --><div class=\"rid_ec9fb40c_123238\" data-apiroot=\"//tools.cdc.gov/api\" data-mediatype=\"HTML\" data-mediaid=\"123238\" data-stripscripts=\"false\" data-stripanchors=\"false\" data-stripimages=\"false\" data-stripcomments=\"false\" data-stripstyles=\"false\" data-cssclasses=\"syndicate\" data-ids=\"\" data-xpath=\"\" data-oe=\"UTF-8\" data-of=\"XHTML\" data-ns=\"\" data-postprocess=\"\" data-nw=\"true\" data-iframe=\"true\" data-cdc-widget=\"syndicationIframe\" data-apiembedsrc=\"//tools.cdc.gov/api/embed/html/js/embed-2.0.3.js\" data-iframeembedsrc=\"//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js\" data-font=\"\"></div><script src='//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js' ></script><noscript>You need javascript enabled to view this content or go to <a href='//tools.cdc.gov/api/v2/resources/media/123238/noscript'>source URL</a>.</noscript>";
webtest.getSettings().setJavaScriptEnabled(true);
webtest.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webtest.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
Log.d("des===",description);
Log.d("failingUrl===",failingUrl);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.d("shouldlLoading===",url);
view.loadUrl(url);
return true;
}
});
webtest.loadData(htmlString, "text/html", null);
}
}

try this code. If you are learning, use official docs > WebView
String htmlString = "<html><body>Your text.</body></html>";
browser.getSettings().setJavaScriptEnabled(true);
browser.loadData(htmlString, "text/html", null);
Your code working fine. I attached screenshot

Related

Android studio Alert dialog block spaces for input in text

I find this more difficult than working on an XML file. How do I block spaces in the text input of an alert dialog? For example, how does it work because I didn't find much information about this on the internet. Thank you
private void RequestNewGroup()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
builder.setTitle("Enter Group Name ");
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
groupNameField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});
builder.setView(groupNameField);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
String groupName = groupNameField.getText().toString();
if (TextUtils.isEmpty(groupName))
{
Toast.makeText(MainActivity.this, "Please write Group Name...", Toast.LENGTH_SHORT).show();
}
else
{
CreateNewGroup(groupName);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
builder.show();
}
I find this more difficult than working on an XML file.
You could (and probably should) create custom dialogs that have their own view/XML file.
To do this, extend DialogFragment:
public class MyDialog extends DialogFragment {
EditText editText;
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// get your custom layout
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.my_custom_layout, null);
builder.setView(view).setCancelable(false);
editText = view.findViewById(R.id.editText);
// add your code here
}
}
XML (R.layout.my_custom_layout):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="foo"
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
android:inputType="textFilter" />
</androidx.constraintlayout.widget.ConstraintLayout>
and in MainActivity:
public void openDialog(Context context) {
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(), "myDialog");
}
also check Android disable space only for Edittext to disable space from XML and
https://www.youtube.com/watch?v=ARezg1D9Zd0&t=446s&ab_channel=CodinginFlow for a more in depth tutorial on custom dialogs and how to send and recieve info from them.

Android WebView evaluateJavascript Uncaught ReferenceError

Currently I'm trying to figured out which is the best way to invoke javascript from android.
AndroidJSCore. AndroidJSCore
WebView
I've tried AndroidJSCore, it's great. But it would enlarge the apk size.
Then I trying to dive into WebView to invoke javascript. But fail.
Activity look like this:
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
private static final String TAG = WebViewActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportZoom(true);
webSettings.setDisplayZoomControls(true);
webView.loadUrl("file:///android_asset/jsWeb/test.html");
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
String test1 = "permissionRegist(\"'function'\", [\"'319609831167500021'\",\"'319609831167500022'\",\"'319609831167500023'\",\"'419609839767500020'\",\"'644731700926740003'\",\"'644731700926740004'\",\"'854885785357389824'\",\"'854995673156816896'\",\"'855001385022918656'\",\"'855009454683459584'\",\"'855298661779902464'\",\"'855303143108513792'\",\"'855347061611171840'\",\"'855356859882803200'\"])";
String test2 = "evalJSExpression()";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(test1, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d(TAG, s);
}
});
webView.evaluateJavascript(test2, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d(TAG, s);
}
});
}
}
});
}
}
there appending files are:
android.js
function permissionRegist(type, list) {
var s_permissionMap = new Map();
s_permissionMap.set(type, list);
}
function evalJSExpression() {
var result = 'dddddd';
return result;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LogicalExpression</title>
<!-- 导入script -->
<script type="text/javascript" src="android.js"></script>
</head>
<body>
<!--<button onClick="permissionRegist()">点击读取文件</button>-->
</body>
</html>
but the result is :
I/chromium: [INFO:CONSOLE(2)] "Uncaught ReferenceError: Map is not defined", source: file:///android_asset/jsWeb/android.js (2)
D/WebViewActivity: null
D/WebViewActivity: "dddddd"
Have you tried https://github.com/mozilla/rhino
here is an example : http://lifeofcoding.com/2015/04/05/Execute-JavaScript-in-Android-without-WebView/
AndroidJSCore is a great lib for android to invoke javascript without WebView.
It seems that Both Native WebView and rhino might have some compilable issues due to the different versions of javascript.
Welcome to contact me about this.
I would find out why when I have time.

webview date picker works in android emulator but not on device?

I've used the code example posted here calling date picker from javascript and this works fine in the android emulator. When I click on the date input box in web view, the android date picker appears and I can select it.
However, when I test this on my device, I just get a standard text input field it is as though the method is not being called. Does anyone have any suggestions? The full code I am using is:
public class MainActivity extends ActionBarActivity {
public WebView mWebView;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
mWebView.addJavascriptInterface(myJavaScriptInterface, "MyJavaScriptInterface");
mWebView.loadUrl("http:// mywebsite.html");
}
// Classe de prise en charge du java privé
public class MyJavaScriptInterface {
public String m_szTagId;
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void openDatePickerDialog(String szTagId) {
m_szTagId = szTagId;
Calendar c = Calendar.getInstance();
DatePickerDialog dp = new DatePickerDialog(mContext, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
String szDate = String.format("%04d/%02d/%02d", year, monthOfYear + 1, dayOfMonth);
mWebView.loadUrl("javascript:callFromActivity_RetDate(\"" + m_szTagId + "\", \"" + szDate + "\")");
}
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
dp.show();
}
} // Class MyJavaScriptInterface
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and the Javascript code is:
// ---- date picker to call methods of the android device
$('#datepicker').click(function(e){
getDataDate();
});
function getDataDate(){
MSSAndroidFunction.openDatePickerDialog('datepicker');
}
function callFromActivity_RetDate(datepicker, data) {
document.subHours.datepicker.value = data;
}
You have named your JavaScript Interface as MyJavaScriptInterface, so you must call it from JavaScript.
I.e.:
Instead of MSSAndroidFunction.openDatePickerDialog('datepicker'), you must do MyJavaScriptInterface.openDatePickerDialog('datepicker'), in a JavaScript method.
I have a WebView based application, in which I define the Interface in another class, not an inner class, and in the initialization I do:
htmlInterface=new HTMLInterface(this, webView);
webView.addJavascriptInterface(htmlInterface, "Android");
Hope it helps you
Regards

How can I turn one specific audio file on or off with CheckBox or toggle button from one activity to another in android?

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class Settings_Menu extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_menu);
TurnSoundOff();
}
private void TurnSoundOff() {
final CheckBox TurnSoundOff= (CheckBox) findViewById(R.id.StartupsoundoffBox);
TurnSoundOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (TurnSoundOff.isChecked()){
mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile); //errors at .create since I can't use a class
mp.stop();
}else{
mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile);
mp.start();
}
}});
}
}
Here is my code, i'm just trying to shutoff or turn on a designated audio file from when the app opens. I have the Checkbox or toggle button in another activity. I'm using media player and some what new to android coding thanks for reading. I setup a settings action from tapping overflow then the settings button to go to activity and I want the audio shutoff or back on in the MainActivity.xml when the check is click from the settings activity. thanks again for reading and help in advance. It errors at .create since I can't use a class
You have to do this using shared preferences . It is very simple.. Instead of making an activity make a preference screen.. Follow these steps..:-
1) Go to resource folder.
2) make a new folder called 'xml'.
3) In xml folder you created make a xml file called 'prefs.xml'.
in that sdd the following code..:-
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:defaultValue="false"
android:key="music"
android:summary="Tick to listen the music"
android:title="Intro Music" >
</CheckBoxPreference>
</PreferenceScreen>
now go to ur activity that plays the song..
ourSong = MediaPlayer.create(Splash.this, R.raw.splash_sound);
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean music = getPrefs.getBoolean("music", true);
if (music == true)
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
};
timer.start();
this thread is used for the timer of your activity.. if u dnt want any timer delete the thread.. the value in the sleep(****) is the time in miliseconds.
add this function also to stop the song after the activity is changed..
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
To get the overflow menu :-
1)make a new folder called menu
2)make a xml file.. add the following code.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:title="Preferences"
android:id="#+id/preferences" />
<item android:title="Exit"
android:id="#+id/exit" />
</menu>
In you actvity add the following code..So that prefernece could be called
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.preferences:
Intent b = new Intent("com.example.code.PREFS");
//instead of 'com.example.code' write your package name
startActivity(b);
break;
case R.id.exit:
finish();
break;
}
return false;
}
And in the end make a class called Prefs and add the following code..
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
Finally add the class in the manifest.. code for that..
<activity
android:name="com.example.code.Prefs"
android:label="Preferences" >
<intent-filter>
<action android:name="com.example.code.PREFS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
your action name should be same as u mentioned in the intent in onMenuItemSelected()...
This would do the trick... :) Peace...

Android use java script to highlight text in webview

I am using webview to render html file and i used java script to highlight (Hello) word in html
public class MyActivity extends Activity{
WebView myWebView;
TextView myResult;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myResult = (TextView)this.findViewById(R.id.myResult);
myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
String txt="Hello";
myWebView.loadUrl("javascript:var text='"+ txt+ "';if (window.find) {document.designMode ='on';var sel = window.getSelection();sel.collapse(document.body, 0);while (window.find(text)) { document.execCommand('HiliteColor', false, 'red');sel.collapseToEnd();}document.designMode = 'off';} else if (document.body.createTextRange) { var textRange = document.body.createTextRange(); while (textRange.findText(text)) {textRange.execCommand('BackColor', false, 'red'); textRange.collapse(false);}}");
myWebView.addJavascriptInterface(new JavaScriptHandler(this), "MyHandler");
}
and this my html
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
this code is run good in debug mode i mean that it already highlight (hello) but in running mode it did not why???????????
i do not know what it mean that running good in debug mode but not in running mode?

Categories

Resources