I am new in android development, I am create an apps to store selected webview content into sqlite database. When user select of word, custom contextual action bar will display in webview. And now I need to get selected word in WebView. Any idea on how to get selected word in WebView and return as String?
Thanks
The only way to get text selection from a WebView is based on javascript. This is not specific to the action mode, this is how WebView text selection is supposed to be retrieved according to WebView developers' point of view. They deliberately decided to not provide an API to access text selection from Java.
The solution comprise 2 approaches.
With Android API >= 19 you can use evaluateJavascript:
webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
On older builds your only resort is a custom javascript interface with a single method accepting String, which you should call via webview.loadUrl passing the same thing:
webview.loadUrl("javascript:js.callback(window.getSelection().toString())");
where js is the attached javascript interface:
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(), "js");
and
public class WebAppInterface
{
#JavascriptInterface
public void callback(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
}
Reference:
How to get the selected text of webview in ActionMode override
Related
I have gone through multiple question on stack overflow but could not find working answer. I need to hide html elements with no id and class name in webview android.
First of all it's probably impossible to do it in Java so you need to do it in Javascript. Second problem is that I don't think there is a simple or good enough way to do that. If you own the HTML page try to add id or class to elements you want to hide.
When you do that you can run it like this:
String classToHide = "some-class";
String jsCode = "for (let el of document.querySelectorAll('." + classToHide + "')) el.style.visibility = 'hidden';";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(jsCode, null);
} else {
webView.loadUrl("javascript:" + jsCode);
}
Note that you need javacsript enabled like this:
webView.getSettings().setJavaScriptEnabled(true);
Android : How to accomplish auto field calculations in PDF Using qoppa library.
My Usecase: In my android app, i have PDF form with three fields. If you change Field A or Field B, Field C will be recalculated to be the sum of Field A and Field B values.
Note : To create form fields and add add JavaScript you will need to have a PDF form designer such as PDF Studio (Qoppa’s desktop PDF editor) or Adobe Acrobat.
Added image shows you the pdf with javaScript Enabled calculations are performing. Opened using AdobeReader and modified FieldB value and click outside, then FieldC will be updated with Total value automatically.
When i open the same document in my android app using below snippet auto calculations are not performing. Need Support in this context...
private void openDocumentUsingQoppa() {
// Enable JavaScript
JavaScriptSettings.setJSEnabled(JavaScriptSettings.ALWAYS);
StandardFontTF.mAssetMgr = getAssets();
try {
pdfDoc = new PDFDocument(strFilePath, null);
PDFDocument.setKey("XXXXXXXXXXXX"); //, this
} catch (PDFException e) {
e.printStackTrace();
}
viewer = new QPDFNotesView(this);
viewer.setActivity(this);
setContentView(viewer);
if(pdfDoc != null) viewer.setDocument(pdfDoc);
}
I assume you are using Qoppa's QPDFNotesView which can display and fill interactive PDF forms on Android. You will need to enable JavaScript for the JavaScript calculations to happen in QPDFNotesView.
public class JavaScriptActivity extends Activity
{
public QPDFNotesView notes;
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
JavaScriptSettings.setJSEnabled(JavaScriptSettings.ALWAYS);
notes = new QPDFNotesView(this);
notes.setActivity(this);
setContentView(notes);
}
}
I want to save my webview to a PDF file. I know that I can print the WebView with WebView.createPrintDocumentAdapter() and PrintManager.print().
But I need a way to save the PDF, that is generated internally by the PrintDocumentAdapter, directly without any user interactions, because I need the file for further processing inside my app.
Any ideas?
I realise this question is quite old now. But I have just realised how this can be sensibly done.
Essentially as per the question you can use the createPrintDocumentAdapter method mentioned above and pass the result to your own "fake" PrintManager implementation which simply overrides the onWrite method to save the output to your own file. The snippet below shows how to take any PrintDocumentAdapter and send the output from it to a file.
public void print(PrintDocumentAdapter printAdapter, final File path, final String fileName) {
printAdapter.onLayout(null, printAttributes, null, new PrintDocumentAdapter.LayoutResultCallback() {
#Override
public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
printAdapter.onWrite(null, getOutputFile(path, fileName), new CancellationSignal(), new PrintDocumentAdapter.WriteResultCallback() {
#Override
public void onWriteFinished(PageRange[] pages) {
super.onWriteFinished(pages);
}
});
}
}, null);
}
As you can see there's quite a few nulls passed into the adapters methods but I have checked the Chromium source code and these variables are never used so the nulls are ok.
I created a blog post about how to do it here:
http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/
Create a custom WebViewClient (reference) and set it on your WebView.
In this WebViewClient you should override shouldOverrideUrlLoading (WebView view, String url). From here on you can download the PDF manually when it is clicked.
I'm struggling implementing a custom validator in my Android app.
I want to show in a list view some suggestions retrieved from a server (which works correctly) even if the don't start with the same letters of the text in my AutoCompleteTextView.
So, i.e. if I write "n" i'd like to get the server response, wich is "r".
So, i tried to implement a validatore setting up the isValid sample which controls if the server response is not empty.
I show my code here:
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setValidator(new Validator());
autoCompleteTextView.performValidation();
and here Validator class:
class Validator implements AutoCompleteTextView.Validator {
public boolean isValid(CharSequence text) {
Log.v("Test", "Checking if valid: ");
int i = 0;
if (!MainActivity.interventos.isEmpty()) {
return true;
}
return false;
}
public CharSequence fixText(CharSequence arg0) {
// TODO Auto-generated method stub
return null;
}
isValid() returns me always False, but it should return me True because MainActivity.interventos is not empty.
Ps: The entire method works good if the server responses with a word which starts with the same letters as in AutocompleteTextView.
Suggestion?
Thanks in advance
I had a similar problem which I worked out using a CustomArrayAdapter with A viewHolder implements a filter to get data from server. So, you can show in AutoComplete list data you need.
And so validator is not useful and you don't need it.
Enjoy and keep me up!!
I am trying to make clickable links in text strings that launch an activity when clicked. I have used Linkify() to detect links in my text. This function is capable of adding links to text, but only web URLs. I need to turn my output into a ClickableSpan so that I can implement this technique.
How do I get Linkify()'s identified links to become ClickableSpans which direct to an activity?
Below is the code I have used in Linkify:
// Linkify parameters
final static Pattern pattern = Pattern.compile("\\[[^]]*]"); // defines the fact that links are bound by [square brackets]
final String scheme = "http://"; // TODO: Currently this is just a blank link
Linkify.addLinks(linkText, pattern, scheme);
For what you want to achieve, it's probably simpler to just override the startActivity() method in your Activity and intercept the ACTION_VIEW intents with the URLs in your text. Something like this:
public class MyActivity extends Activity {
#Override
public void startActivity(Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_VIEW)) {
// launch our other activity instead
Intent ourIntent = new Intent(this, MyOtherActivity.class);
ourIntent.setData(intent.getData());
super.startActivity(ourIntent);
// we're done!
return;
}
// else, normal handling by the framework
super.startActivity(intent);
}
// the rest of your activity code
}
For reference, here's the source code for URLSpan which will trigger the startActivity() method above.
How do I get Linkify()'s identified links to become ClickableSpans which direct to an activity?
After your call to addLinks(), call getText() to retrieve the Spanned object from the TextView. This object will have a series of URLSpan objects, one per matched link -- you can get an array of those through a call to getSpans(). You will need to note where each those spans start and end (via getSpanStart() and getSpanEnd()), remove the URLSpan, and replace it with your own spans to do what you want.