Android studio Alert dialog block spaces for input in text - javascript

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.

Related

Javafx webEngine executescript() cant send multiline string

Problem: I cant seem to find a way for javafx webengine to fire javascript function if I use a java String object with multiple line.
If I enter the following example in html: "asd" ENTER "qwe" in the input textArea then CLICK send button. The following java code wont run:
webEngine.executeScript("onRecieveMsg('" + msg + "')");.
But it will work if I don't use ENTER in input textArea.
Please help me
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Chat</title>
</head>
<script type="text/javascript">
function onSendMsg(){
var msg = document.getElementById("inputTextArea").value;
document.getElementById("inputTextArea").value = "";
java.onSendMsg(msg);
}
function onRecieveMsg(msg){
var msg = msg;
msg = document.getElementById("outputTextArea").value + msg;
document.getElementById("outputTextArea").value = msg + "\n";
}
</script>
<body>
<h1>Output</h1>
<textarea id="outputTextArea" rows="10" cols="50" readonly></textarea>
<h1>Input</h1>
<textarea id="inputTextArea" rows="4" cols="50"></textarea>
<button id="sendBtn" onclick="onSendMsg()">Send</button>
</body>
</html>
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class ViewFx extends Application {
//VARIABLES
private WebView webView;
private WebEngine webEngine;
private WebEngineListener webEngineListener;
private JsBridge jsBridge;
//CONTRUCTOR
//METHODS
#Override
public void start(Stage stage) {
webView = new WebView();
webEngine = webView.getEngine();
webEngine.load(getClass().getResource("view.html").toExternalForm());
jsBridge = new JsBridge();
webEngineListener = new WebEngineListener(jsBridge);
webEngine.getLoadWorker().stateProperty().addListener(webEngineListener);
stage.setScene(new Scene(webView));
stage.setWidth(600);
stage.setHeight(700);
stage.show();
}
//INNER CLASS
private class WebEngineListener implements ChangeListener<State> {
//VARIABLES
private JsBridge jsBridge;
private JSObject jsobj;
//CONSTRUCTOR
private WebEngineListener(JsBridge jsBridge) {
this.jsBridge = jsBridge;
}
//METHODS
#Override
public void changed(ObservableValue<? extends State> observable, State oldState, State newState) {
if(newState == State.SUCCEEDED) {
jsobj = (JSObject) webEngine.executeScript("window");
jsobj.setMember("java", jsBridge);
}
}
}
public class JsBridge {
//VARIABLES
//CONTRUCTOR
//METHODS
public void onSendMsg(String msg) {
webEngine.executeScript("onRecieveMsg('" + msg + "')");
}
}
public static void main(String[] args) {
launch(args);
}
}
Multiline string literals neither work in JavaScript nor in java. In case of a multiline message being received you simply execute invalid JavaScript code:
message received
asd
qwe
Executed javascript
onRecieveMsg('asd
qwe')
You need to escape newline instead of including them in the script. There are a few more characters that require being quoted. You could use a method like this to get a properly quoted string:
public static String toJavaScriptString(String value) {
value = value.replace("\u0000", "\\0")
.replace("'", "\\'")
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
return "\""+ value+"\"";
}

Load WebView with Embedded HTML code - Android

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

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...

Not able to search the contacts in android application

In my application i need to search the phone contact numbers and I want to select a number and I want to save that number and after that once I click, send button message should go to that number. Here am using more than two activities and am searching a contacts inside of one such activity..
please any one can help me..thanks in advance..
Here is my code.
public class SearchNum extends Activity {
private TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchnum);
resultText = (TextView)findViewById(R.id.searchViewResult);
setupSearchView();
}
private void setupSearchView() {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) findViewById(R.id.searchView);
SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
searchView.setSearchableInfo(searchableInfo);
}
#Override
protected void onNewIntent(Intent intent) {
if (ContactsContract.Intents.SEARCH_SUGGESTION_CLICKED.equals(intent.getAction())) {
//handles suggestion clicked query
String displayName = getDisplayNameForContact(intent);
resultText.setText(displayName);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// handles a search query
String query = intent.getStringExtra(SearchManager.QUERY);
resultText.setText("should search for query: '" + query + "'...");
}
}
private String getDisplayNameForContact(Intent intent) {
Cursor phoneCursor = getContentResolver().query(intent.getData(), null, null, null, null);
phoneCursor.moveToFirst();
int idDisplayName = phoneCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String name = phoneCursor.getString(idDisplayName);
phoneCursor.close();
return name;
}
}
and my xml file for search view is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SearchNum" >
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</SearchView>
<TextView
android:id="#+id/searchViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:text="#string/hello_world" />
</RelativeLayout>
Then my searchable file in xml folder is
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/findContact"
android:hint="#string/findContact"
android:includeInGlobalSearch="true"
android:queryAfterZeroResults="true"
android:searchMode="queryRewriteFromText"
android:searchSettingsDescription="#string/findContact"
android:searchSuggestAuthority="com.android.contacts"
android:searchSuggestIntentAction="android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"
android:searchSuggestIntentData="content://com.android.contacts/contacts/lookup" >
<!-- allow green action key for search-bar and per-suggestion clicks -->
<actionkey
android:keycode="KEYCODE_CALL"
android:queryActionMsg="call"
android:suggestActionMsg="call" />
</searchable>
and also i have taken permission in my manifest file
<uses-permission android:name="android.permission.READ_CONTACTS" />
in activity i put
<action android:name="android.intent.action.SEARCH" />
and also here is my metadata
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
You also need to add to your manifest file:
android:launchMode="singleTop"
Link: http://looksok.wordpress.com/2013/06/15/android-searchview-tutorial-edittext-with-phone-contacts-search-and-autosuggestion/

Categories

Resources