Points Covered
- Data Types
- Async Tasks
- Logging
- DialogBox
- WebView
- SuppressLint
Data types
Array Equivalent
- // declaring a list of integer
private ListList;
// reserving the space for list elements
List = new ArrayList(3); - ArrayList
nameValuePairs = new ArrayList ();
nameValuePairs.add(new BasicNameValuePair("Your_var_1", value));
nameValuePairs.add(new BasicNameValuePair("Your_var_2", value)); - Map<String, List
> assocArr = {
'title1': ['haha', 'hehe'],
'huhuh3': ['hihihi', 'huhuhu']
};
refer
print(assocArr); // {title1: [haha, hehe], huhuh3: [hihihi, huhuhu]}
print(assocArr['title1']); // [haha, hehe] - JSONArray jArray = new JSONArray(String_Response);
JSONObject json_data = jArray.getJSONObject(i);
Async Task
Logging
Log Class
Generally, you should use the Log.v(), Log.d(), Log.i(), Log.w(), and Log.e() methods to write logs.
You can then view the logs in logcat.
Parameters:
(String tag/used to identify source of log message . clould be null/, String msg)
Dialog box
https://code.tutsplus.com/tutorials/showing-material-design-dialogs-in-an-android-app--cms-30013
WebView
Important Points to note
- Add WebView in layout
- Add permissions in AndroidManifest.xml
- Set WebSettings for enabling javascript operations
val webSettings: WebSettings = webView.settings webSettings.javaScriptEnabled = true
- Add WebAppInterface4CallsFromJS (custom object) as interface for web page to android app
- Add
CustWebViewClient extends WebViewClient
for handling events that impact content rendering. You can also use this subclass to intercept URL loading. - Add WebChromeClient (instance of
android.webkit.WebChromeClient
)for showing onConsoleMessage in logcat (also inchrome://inspect/devices
), enable fullscreen display etc. - Add DownloadListener for downloading eg: pdfs etc
To add a WebView to your app, you can either include the <WebView>
element in your activity layout, or set the entire Activity window as a WebView in onCreate()
.
- To add a WebViewto your app in the layout, add the following code to your activity's layout XML file:
<WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent" />
To load a web page in the WebView, use loadUrl(). For example:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
- To add a WebView to your app in an activity’s onCreate() method instead, use logic similar to the following:
WebView myWebView = new WebView(activityContext);
setContentView(myWebView);
Then load the page with:
myWebView.loadUrl("https://www.example.com");
Or load the URL from an HTML string:
// Create an unencoded HTML string
// then convert the unencoded HTML string into bytes, encode
// it with Base64, and load the data.
String unencodedHtml =
"<html><body>'%23' is the percent code for ‘#‘ </body></html>";
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),
Base64.NO_PADDING);
myWebView.loadData(encodedHtml, "text/html", "base64");
Before this works, however, your app must have access to the Internet. To get internet access, request the INTERNET permission in your manifest file. For example:
<manifest ... >
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
Also check
1.WebChromeClient : Enabling fullscreen support with WebChromeClient. This class is also called when a WebView needs permission to alter the host app's UI, such as creating or closing windows and sending JavaScript dialogs to the user. To learn more about debugging in this context, read Debugging Web Apps.
2.WebViewClient : Handling events that impact content rendering, such as errors on form submissions or navigation with WebViewClient. You can also use this subclass to intercept URL loading.
- WebSettings : Enabling JavaScript by modifying WebSettings.
Enable JavaScript
JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView.You can retrieve WebSettings with getSettings(), then enable JavaScript with setJavaScriptEnabled().
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebSettings provides access to a variety of other settings that you might find useful. For example, if you're developing a web application that's designed specifically for the WebView in your Android app, then you can define a custom user agent
string with setUserAgentString(), then query the custom user agent in your web page to verify that the client requesting your web page is actually your Android app.
Bind JavaScript code to Android code
To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
You can bind this class to the JavaScript that runs in your WebView with addJavascriptInterface() and name the interface Android. For example:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
For example, here's some HTML and JavaScript that creates a toast message using the new interface when the user clicks a button:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
Handle page navigation
To open links clicked by the user, provide a WebViewClient for your WebView, using setWebViewClient(). For example:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(MyWebViewClient);
If you want more control over where a clicked link loads, create your own WebViewClient that overrides the shouldOverrideUrlLoading()
method. The following example assumes that MyWebViewClient is an inner class of Activity.
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if ("www.example.com".equals(request.getUrl().getHost())) {
// This is my website, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
startActivity(intent);
return true;
}
}
Then create an instance of this new WebViewClient for the WebView:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
Handle custom URLs
if you implement callbacks such as shouldOverrideUrlLoading() or shouldInterceptRequest(), then WebView invokes them only for valid URLs.
For example, WebView may not call your shouldOverrideUrlLoading() method for links like this:
<a href="showProfile">Show Profile</a>
Invalid URLs like above are handled inconsistently in WebView, so we recommend using a well-formed URL instead, such as using a custom scheme or using an HTTPS URL for a domain that your organization controls.
Instead of using a simple string in a link as shown earlier, you can use a custom scheme such as the following:
<a href="example-app:showProfile">Show Profile</a>
You can then handle this URL in your shouldOverrideUrlLoading() method like this:
// The URL scheme should be non-hierarchical (no trailing slashes)
private static final String APP_SCHEME = "example-app:";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(APP_SCHEME)) {
urlData = URLDecoder.decode(url.substring(APP_SCHEME.length()), "UTF-8");
respondToData(urlData);
return true;
}
return false;
}
The shouldOverrideUrlLoading()
API is primarily intended for launching intents for specific URLs. When implementing it, make sure to return false for URLs the WebView should handle
. You're not limited to launching intents, though; you can replace launching intents with any custom behavior in the preceding code samples.
Navigate web page history
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
Handle device configuration changes
During runtime, activity state changes occur when a device’s configuration changes, such as when users rotate the device or dismiss an input method editor (IME). These changes cause a WebView object's activity to be destroyed and a new activity to be created, which also creates a new WebView object that loads the destroyed object's URL. To modify your activity’s default behavior, you can change how it handles orientation changes in your manifest. To learn more about handling configuration changes during runtime, read Handling configuration changes.
Opening New Windows
By default, requests to open new windows are ignored. This is true whether they are opened by JavaScript or by the target attribute in a link. You can customize your WebChromeClient to provide your own behavior for opening multiple windows.
Android to JS
JavaScript function call without return value
webview.loadUrl("javascript:myTestFunction();");
JavaScript function call with return value
webView.evaluateJavascript("javascript:myTestFunction();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
// Do what you want with the return value
}
});
Android to PHP
@SuppressLint
SuppressLint is an annotation used by the Android Lint tool.
Lint will tell you whenever something in your code isn't optimal or may crash. By passing NewApi there, you're suppressing all warnings that would tell you if you're using any API introduced after your minSdkVersion
See a full list of Lint checks - including "NewApi" - here: http://tools.android.com/tips/lint-checks
|
|