Make a bold text in Android Java activity and call it - java

I want to make a bold text in my activity and show it in a dialog box.
I did it (I think) but I don't know how should I call it in my dialog box.
I'm trying in with HTML format:
String text = "<b>" + "My text" + "</b> " + "is bold";
StringCharacterIterator tv = null;
tv.setText(Html.fromHtml(text ));
Here it should work, but how can I call the "tv"?
I'm trying this way:
builder.setMessage(tv);
...but isn't working since the error is:
error: incompatible types: Spanned cannot be converted to String tv.setText(Html.fromHtml(text ));

You can create custom dialog box(example: How to create a Custom Dialog box in android?) and set your string like below.
String text = "<b>My text</b> is bold";
TextView tv = yourdialog.findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text));

I answer by myself:
builder.setMessage(Html.fromHtml("<b>Write something" + "</b> " + "here"));

Related

Highlight text in webview and save it

I have a webview that I display some html texts (I have them in assets). I'd like to allow users to highlight some parts of it.
I was thinking in some solutions:
try to put the texts user hightlight in a shared pref and use:
webview.findAllAsync(shared_pref_string);
webview.setFindListener(new FindListener() {
#Override
public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
// try to select the texts.
}
});
The problem I see is, user can select one word, like "what", and this code will select all "whats" the text has.
Use javascript:
public static String Highlightscript = " <script language="javascript">" +
"function highlightSelection(){" +
"var userSelection = window.getSelection();" +
"for(var i = 0; i < userSelection.rangeCount; i++)"
+ " highlightRange(userSelection.getRangeAt(i));" +
"}" +
"function highlightRange(range){"+
"span = document.createElement(\"span\");"+
"span.appendChild(range.extractContents());"+
"span.setAttribute(\"style\",\"display:block;background:#ffc570;\");"+
"range.insertNode(span);}"+
"</script> ";
webView.loadUrl("javascript:highlightSelection()");
But this 2 solutions not seems nice to me, any other best way to do this and more modern?
this android library is implemented what you need:
https://github.com/FolioReader/FolioReader-Android
they are using this javascript library https://github.com/timdown/rangy, maybe this will make sense.

Default button with JOptionsPane not working properly

I posted this code yesterday for another issue but now I once again must call on you all for help.. I appreciate all the assistance so far I have had without this community I wouldn't have made it so far.
Now, my problem is quite simple. I have a GUI with an input box for the user and three buttons. The buttons are not JButtons, they are the standard JOptionsPane yes, no, and cancel buttons. I did change the text to "next entry", "next batch", and "finished".
Before I made changes to my GUI I had standard buttons. The button that will most often be used is the "yes" button (now "next entry").. This button will be clicked a LOT in my program. Before the default button setting worked.. A user could simply type a number and press enter quickly. Now the enter key will not activate the default button instead the user must physically click on it.. This is what I want to change.
Is there any way I can set the below code so when the user clicks enter, regardless of what text they have typed, the "yes" (now "next batch" is clicked on default)? For what it's worth I did do research on this but could not find a solution that suited my specific circumstances.
package nacha;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Testing4
{
public static void main(String args[]){
String css = "<span style='font-size:10; color: white; background-color:black'>";
String batchCss = "<span style='font-size: 20'>";
String endSpanCss = "</span>";
String table = "<table border=4>";
String endTable = "</table>";
String mainCss = "<span style='font-size:12; color: red'>";
String header1Css = "<span style = 'font-size:15; font-weight:bold;text-decoration:underline;border:1px dotted red'>";
String text1Css = "<span style = 'font-size:12; font-style:italic'>";
String text = "<html>" +
css + batchCss + "1 of 2"+endSpanCss+endSpanCss+ endSpanCss +
"<br><br><br>"+header1Css+"Entry Detail:"+endSpanCss +
"<br>"+mainCss+"111111111111111111111"+endSpanCss+
"<br><br><br>"+text1Css+"Please type 1-21 to apply a reason code and addenda record to the entry detail." +
"<br>Please type 'h' and press the next entry button to open the help screen."+endSpanCss +
"<br><br><br>"+header1Css+"Reason Codes"+ endSpanCss +
"<br>"+table+"R01 - Insufficient Funds" +
"<br>R02 - Account Closed" +
"<br>R03 - No Account" +
"<br>R04 - Invalid Account Number" +
"<br>R05 - Unauthorized Debit to Consumer Account" +
"<br>R06 - Returned per ODFI Request" +
"<br>R07 - Auth Revoked by Customer" +
"<br>R08 - Payment Stopped" +
"<br>R09 - Uncollected Funds" +
"<br>R10 - Customer Advises Not Authorized" +
"<br>R11 - Check Truncation Entry Return" +
"<br>R12 - Branch Sold to Another DFI" +
"<br>R13 - Invalid ACH Routing Number" +
"<br>R14 - Represenative Payee Deceased or Unable to Continue" +
"<br>R15 - Beneficiary or Account Holder Deceased" +
"<br>R16 - Account Frozen" +
"<br>R17 - File Record Edit Criteria" +
"<br>R18 - Improper Effective Entry Date" +
"<br>R19 - Account Field Error" +
"<br>R20 - Non-Transaction Amount" +
"<br>R21 - Invalid Company Information" +
"<br>R22 - Invalid Individual ID Number"+endTable;
//Below code creates the GUI for the return builder portion of the program.
Object[] options1 = {"Next Entry","Next Batch","Finished"};//Changes the default buttons.
BorderLayout border = new BorderLayout();
JPanel panel = new JPanel();
panel.setLayout(border);
panel.add(new JLabel(text),BorderLayout.NORTH);//Adds the label to the top of the panel.
JTextField textField = new JTextField(10);
panel.add(textField,BorderLayout.SOUTH);//Adds a user-input text area to the bottom of the panel.
int result = JOptionPane.showOptionDialog(null, panel, "Return Builder", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, JOptionPane.YES_OPTION);
}
}
You need to pass the default option as the final argument to JOptionPane.showOptionDialog:
int result = JOptionPane.showOptionDialog(null, panel, "Return Builder",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options1, options1[0]);
This will have the side effect of making that button have the initial keyboard focus whenever the dialog is displayed. If you don't want that, you can force the JTextField to receive the focus whenever it is displayed in a window:
textField.addHierarchyListener(new HierarchyListener() {
#Override
public void hierarchyChanged(HierarchyEvent e) {
final Component c = e.getComponent();
long flags = e.getChangeFlags();
if ((flags & HierarchyEvent.SHOWING_CHANGED) != 0 &&
c.isShowing()) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
c.requestFocusInWindow();
}
});
}
}
});
A side note: For asking the user to select from a list of known options, a JComboBox is a better choice than a JTextField. Your Help option can simply be a different JButton, present in the message body of the JOptionPane.

Automatic clicking an button in JavaFX Webview

I am working an an JavaFX Webbrowser that can autologin to some sites, i know how to set the data to username and password fields but how to i make it execute the login button click?
This is what i got so far:
String email = "document.getElementsByName('email')[0].value='MY_EMAIL';";
String pass = "document.getElementsByName('pass')[0].value='MY_PASSWORD';";
String login = "";
webEngine.executeScript(email);
webEngine.executeScript(pass);
webEngine.executeScript(login);
and this is the javascript code of the button it should click:
<label class="uiButton uiButtonConfirm" id="loginbutton" for="u_0_c"><input value="Aanmelden" tabindex="4" type="submit" id="u_0_c"></label>
this is a concentrated, non-specialized example... uses the dom.w3c.Node.* package
HTMLInputElement element = (HTMLInputElement)myWebView.getEngine().getDocument().getElementsByTagName("input").item(0);
element.click();
Find a way to handle the object you're looking for, and it will work.
I haven't tried that, but it should work. The idea is add jQuery to the loaded page and then to use it to click the button. This post explains how to do this with JS: How Do I Add jQuery To Head With JavaScript? So with Java it should be (I've copied the first answer into a string and executing it with the web engine):
String script = "script = document.createElement('script');\n" +
"\n" +
"script.onload = function() {\n" +
" // jQuery is available now\n" +
"};\n" +
"var head = document.getElementsByTagName(\"head\")[0];\n" +
"\n" +
"script.type = 'text/javascript';\n" +
"script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';\n" +
"\n" +
"head.appendChild(script);";
webEngine.executeScript(script);
This should be done right when WebView is initialized (via webEngine.getLoadWorker().stateProperty().addListener(...)). Note: jQuery is loaded asynchronously.
Now you should be able to click a button with jQuery:
webEngine.executeScript("$('#buttonId')[0].click()");
This post should help you with debugging JS in a WebView: JAVAFX / WebView / WebEngine FireBugLite or Some other debugger?

Fill fields in webview automatically

I have seen this question floating around the internet, but I haven't found a working solution yet. Basically, I want to load my app and press a button; the button action will then fill in a username and password in a website already loaded in the webview (or wait for onPageFinished). Finally, the submit button on the login page will be activated.
From what I understand this can be done by doing a java injection with the loadUrl(javascript), but I don't know what the java commands would be to fill in the fields. The same question was asked for iOS, but the commands are slightly different.
Is it possible to do what I am asking with javascript in a webivew, or do I have to do a http-post without a webview like this or this?
Thank you so much for any help you can give!
Thanks all for your answer, it helped me, but didn't work.
It was allways opening a white page until i found this :
https://stackoverflow.com/a/25606090/3204928
So here complete solution, mixing all infos found here and there :
1) first of all you have to enable DOM storage, if you don't do that, .GetElementByXXX will return nothing (you have to do it before loading the page)
myWebView.getSettings().setDomStorageEnabled(true);
2)Your last Javascript call on GetElementByXXX MUST store the result in a variable
Exemple 1 :
_webview.loadUrl("javascript:var uselessvar =document.getElementById('passwordfield').value='"+password+"';");
here only one call (only one semi-colon) so we immediatly store the result in 'uselessvar'
Example 2 : see user802467 answer
here there is 3 calls (one for login field, one for password field, one to submit button), only the last call need to be store, it's done in 'frms'
Javascript programmers should easily explain this behaviour...
hope this will help
You don't need to use "java commands"... but instead JavaScript... for instance:
String username = "cristian";
webview.loadUrl("javascript:document.getElementById('username').value = '"+username+"';");
So basically, what you have to do is a big string of JavaScript code that will get those fields and put values on them; also, you can enable/disable the submit button from JavaScript.
This worked for me to fill form values and submitting the form:
webView.loadUrl("javascript: {" +
"document.getElementById('username').value = '"+uname +"';" +
"document.getElementById('password').value = '"+password+"';" +
"var frms = document.getElementsByName('loginForm');" +
"frms[0].submit(); };");
Here is complete code which works for me (Bitbucket):
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://example.com/");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String password = "password";
final String username = "username";
final String answer = 5;
final String js = "javascript:" +
"document.getElementById('password').value = '" + password + "';" +
"document.getElementById('username').value = '" + username + "';" +
"var ans = document.getElementsByName('answer');" +
"ans[0].value = '" + answer + "';" +
"document.getElementById('fl').click()";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
} else {
view.loadUrl(js);
}
}
});
I tried #user802467 solution.But there was a different behaviour in 2 things
If I stored ONLY the last javascript call in a variable, it was not filling in the fields. Instead if I stored all the three calls in variables, it did
For some reason my form was not being submitted using submit(). But instead of submitting the form, if I clicked on the submit button using button.click(), I didnot need to store all the three calls and everything worked perfectly!
Here is what I used (but didnt work)
view.loadUrl("javascript: var x = document.getElementById('username').value = '" + username + "';" +
"var y = document.getElementById('password').value = '" + password + "';" +
"var form1 = document.getElementById('loginform');" +
"form1[0].submit(); ");
Here is the code that worked for me
view.loadUrl("javascript: document.getElementById('username').value = '" + username + "';" +
" document.getElementById('password').value = '" + password + "';" +
"var z = document.getElementById('submitbutton').click();"
);
It works for me
webView.loadUrl("javascript:var uselessvar =document.getElementById('regno').value='"+mob+"';",null);
webView.loadUrl("javascript:var uselessvar =document.getElementById('passwd').value='"+pass+"';",null);

Trying to do searchable username from query result

I'm using google app engine to do a website that has some messages, i would like to display the message with a name in form of a link that appointed to the person profile. The only problem is that all my webpages are dynamic and printed from the code.
What I first thought of doing was a link that in click it would call a method in the program with the parameter of the clicked name. The method would then receive the paramet of the name, do a query and print the profile in a new webpage. I think this would work fine. The problem and question i have is how do I do the clickable name with method call.
My code to print the text message to the html page now is:
List<Texto> results = (List<Texto>) query.execute(tituloparam);
if (!results.isEmpty())
{
for (Texto e : results)
{
resp.getWriter().println("Titulo:"
+ results.get(0).titulo);
resp.getWriter().println("Nome:<a href='/author?name=" + results.get(0).autor + "'>" + results.get(0).autor + "</a>");
resp.getWriter().println("Data:"
+ results.get(0).data);
resp.getWriter().println("Texto:"
+ results.get(0).texto);
}
}
So the autor would be the clickable object. Can anyone help me?
Edit 1: Thanks to uwe (Thank you) now I have a clickable object. But how do I call a method with the parameter = autor from there?
You need to add a link to it like this:
resp.getWriter().println("Nome:<a href='/author?name=" + results.get(0).autor + "'>" + results.get(0).autor + "</a>");
Then it shows it as link and makes it clickable.

Categories

Resources