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);
}
}
Related
I am implementing an Android app that is responsible for some data exchange with other services such as credentials. I then want to use that information to automatically fill in the input fields of other applications on the device such as Spotify.
Is there any way to fill the input fields of another app, like the username and password to remove the chore for the user to manually input it?
Also I noticed that at least on iOS, Spotify recognizes 1Password to be installed and displays a small icon next to the input fields with which I can fill the fields from the data stored in 1Password - how is this done as it seems to be another solution to my problem?
Thanks in advance
You might want to implement Autofill Service https://developer.android.com/guide/topics/text/autofill-services.html
There is a ready to use sample app which will get you started https://github.com/googlesamples/android-AutofillFramework
Android will invoke onFillRequest() method giving your service a chance to show autofill suggestions. Here is a sample code from above link:
#Override
public void onFillRequest(FillRequest request, CancellationSignal cancellationSignal, FillCallback callback) {
// Get the structure from the request
List<FillContext> context = request.getFillContexts();
AssistStructure structure = context.get(context.size() - 1).getStructure();
// Traverse the structure looking for nodes to fill out.
ParsedStructure parsedStructure = parseStructure(structure);
// Fetch user data that matches the fields.
UserData userData = fetchUserData(parsedStructure);
// Build the presentation of the datasets
RemoteViews usernamePresentation = new RemoteViews(getPackageName(), android.R.layout.simple_list_item_1);
usernamePresentation.setTextViewText(android.R.id.text1, "my_username");
RemoteViews passwordPresentation = new RemoteViews(getPackageName(), android.R.layout.simple_list_item_1);
passwordPresentation.setTextViewText(android.R.id.text1, "Password for my_username");
// Add a dataset to the response
FillResponse fillResponse = new FillResponse.Builder()
.addDataset(new Dataset.Builder()
.setValue(parsedStructure.usernameId,
AutofillValue.forText(userData.username), usernamePresentation)
.setValue(parsedStructure.passwordId,
AutofillValue.forText(userData.password), passwordPresentation)
.build())
.build();
// If there are no errors, call onSuccess() and pass the response
callback.onSuccess(fillResponse);
}
class ParsedStructure {
AutofillId usernameId;
AutofillId passwordId;
}
class UserData {
String username;
String password;
}
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
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.
There is iOS US2FormValidator library for user input validation (see the picture below). I think that library is better than the default of just popping an alert when something doesn't validate.
I'm looking for how to do such things on Android. Are there some Android analogs of US2FormValidator?
The pop-up effect you have shown on your screenshot can be achieved using Android's built-in setError(String) method on EditText widgets.
Also, you can leverage the power of annotations using the Android Saripaar library that I've authored.
first add the library:
compile 'com.mobsandgeeks:android-saripaar:2.0.2'
The library is very simple to use. In your activity annotate the View references you would like to validate as in the following example.
#Order(1)
private EditText fieldEditText;
#Order(2)
#Checked(message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
#Order(3)
#Length(min = 3, message = "Enter atleast 3 characters.")
#Pattern(regex = "[A-Za-z]+", message = "Should contain only alphabets")
private TextView regexTextView;
#Order(4)
#Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;
#Order(5)
#ConfirmPassword
private EditText confirmPasswordEditText;
The order attribute specifies the order in which the fields have to be validated.
In your onCreate() method instantiate a new Validator object. and call validator.validate() inside any of your event listeners.
You'll receive callbacks on onSuccess and onFailure methods of the ValidationListener.
If you want to show a pop-up as show in the image above then do the following,
public void onValidationFailed(View failedView, Rule<?> failedRule) {
if (failedView instanceof Checkable) {
Toast.makeText(this, failedRule.getFailureMessage(), Toast.LENGTH_SHORT).show();
} else if (failedView instanceof TextView) {
TextView view = (TextView) failedView;
view.requestFocus();
view.setError(failedRule.getFailureMessage());
}
}
Android has extremely easy-to-use built-in validation mechanism which is great enough. See the following link:
http://blog.donnfelker.com/2011/11/23/android-validation-with-edittext/
I've just come across ValidationKomensky that you may find useful
https://github.com/inmite/android-validation-komensky
I'm trying to parse a really simple XML in my android app, for example:
<data>
<section id="123">bla</section>
<area>blabla</area>
</data>
But in every example I find I see how to extract the data in the attribute (id being 123) when what I need to extract is the data displayed - "bla" and "blabla".
How do I do that using SAXParser?
this tutorial respond to exactly what you want hope you gonna enjoy
See how The characters method in the parser handler takes care of extreacting an element's text value
The characters method in the parser handler takes care of an element's text value.
You need to override the characters method.
Well, writing parsers by hand is of course fun & error-prone, I'd however recommend using a framework - even a simple one like the built in android.sax package.
Using the StartElementListener (if you want the attributes at all that is) & EndTextListener (captures the body text of the element):
class Section implements StartElementListener, EndTextElementListener {
String mValue;
String mId;
#Override
public void end(String body) {
mValue = body;
}
#Override
public void start(Attributes attributes) {
mId = attributes.getValue("", "id");
}
}
Listeners of these types are attached to Elements derived from a RootElement, like so:
Section section = new Section();
RootElement data = new RootElement("data");
// Use "requireChild" if a "section" is required as a child of "data".
Element s = data.getChild("section");
s.setStartElementListener(section);
s.setEndTextElementListener(section);
try {
Xml.parse(xml, data.getContentHandler());
} catch (SAXException e) {
}
Basically, this helps you build content handlers for SAX that cares about the hierarchy and keeps track of what element you are parsing easily. Short & nifty code also I guess.