Genymotion is a third party Android Emulator which helps developers to run and test apps. When compared to Android default emulators, It boots fast and quickly runs your app. It uses x86 architecture and make use of OpenGL hardware acceleration, that gives us a smooth operation.
Let’s learn, how to create an account on genymotion.com and download Genymotion.
How to create an account and download Genymotion?
Step 1
Search “genymotion free” on Google or go to “https://www.genymotion.com/fun-zone/”
Step 2
Click on the button named “Download Genymotion Personal Edition”.
Step 3
If you already have a Genymotion account, then you can sign in with your username and password. Otherwise, click on Create an account.
Step 4
Fill up the form with valid details.
Step 5
Tick the checkbox by agreeing on privacy policy, terms, and conditions. Now click on CREATE ACCOUNT button. Now Genymotion sends email to your registered email address.
Step 6
Go to your registered email account and click on the link like above.
Step 7
Click on the link “Download Genymotion for personal use“.
Step 8
I recommend downloading genymotion with Virtual box. If the virtual box is already installed on your pc, then you can select the second option. If you are a Mac or Ubuntu user, scroll down to see the download links.
Then click on the download button based on the operating system.
Download Genymotion virtual devices
Step 9
After downloading, Install Genymotion just like any other software in Windows. At last, launch Genymotion.
If you skip these step or you already installed Genymotion, then double click on the Genymotion icon and launch.
Step 10
When Genymotion launches, you can see a lot of virtual device templates. Select any one of them and click on the 3 vertical dot icon.
Step 11
Click “install” from the menu.
Step 12
You can configure the Genymotion virtual device here.
if you want the virtual keyboard tick on the checkbox Use virtual keyboard for text input, or you can use PC’s Keyboard. Click Install
Step 13
Download started.
Step 14
After the download completion, click on the three vertical dot menu on the right side and click on start.
Step 15
Genymotion virtual device started to load.
Step 16
Genymotion has successfully installed on your PC.
Next section will discuss on Genymotion integration with Android Studio.
Download Genymotion plugin for Android Studio
Step 1
Open Android Studio, go File->Settings
Step 2
1. Click on Plugins
2. Search Genymotion in search dialog box.
3. If genymotion not found, Click on Search repositories or Browse repositories.
3 and 4 are leading to same page.
Step 3
Click the install button.
Step 4
Restart Android Studio for changes to take effect.
Step 5
Click on the restart button
Step 6
After the restart, click on the genymotion icon.
Step 7
Choose Virtual devices from the dialog box and click on Start
Step 8
Now click on the run button, genymotion virtual device will be shown on chooser dialog. Select and Click OK.
Step 9
Done. Genymotion is successfully integrated with Android Studio. Now you can test all your application using the same steps.
How to install gapps or google play services on Genymotion
So many apps rely on google play services. Developers of Genymotion know that, So the latest version of Genymotion arrives with a widget named Open GAPPS. This widget simply installs play store in one click. Let me show you how to install play store on Genymotion.
Step 1
Genymotion provided with a GAPPS icon to install play store. Click on the icon.
Step 2
Click Accept.
Step 3
Download starts.
Step 4
Click on Restart now, it will redirect to GApps website.
Step 5
That’s all, play store is successfully installed.
Step 6
Install your favorite apps and games now.
Why Android Studio not detecting Genymotion device
After the successful installation of Genymotion, I too have faced this problem. Do the below steps to solve
Open genymotion software, on the top-left side, click on genymotion.
Click on settings
Click on ADB
Select the radio button with the label “Use custom Android SDK Tools” , locate your Android SDK through BROWSE button, When the location reaches Android-SDK folder, select and open. If you have selected the proper SDK folder, then it turns out to say this folder is valid.
That’s all. Now Android Studio can launch Genymotion easily.
Conclusion
By reading this post, you already understood that Genymotion is far better than Android default emulator. It boots fast and runs your app in less time, it also provides lots of other features. Although, It lacks wearable support. For making a wear app, you must use Android default ones.
So all I want to say is just give it a try if you never have used Genymoion. Let us know your experience with Genymotion and if you enjoyed reading this article, consider sharing it on Facebook, Twitter, and Pinterest.
In Android, we can use Intent to start another activity. Intent can be used to launch other app activities too. But now we simply describe starting a new activity.
val intent = Intent(this@MainActivity, SecondActivity::class.java)
startActivity(intent)
Intent(Context packageContext, Class cls) – Using this Intent’s constructor, we can create a way to our second activity.
startActivity(Intent intent) – It’s one of the methods in Activity class and launches activity specified in the Intent. If there is no Activity found, ActivityNotFoundException() gets called.
Intent needs a Java reference of class. That’s why We use here class.java part in Kotlin.
Create an Android Studio project
In this example, We just create two activities, when you click on the button, It shows Second Activity. Here I have used OnClickListener for click events, You can also use android:onClick”attribute.
Okay.
Open Android Studio and start a new Android Studio project.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
1. Using Strike – Android TextView StrikeThrough XML example
Like Html, <Strike> tag easily creates a horizontal line through our TextView content. Create a string element in strings.xml and place text which you want to get strikethrough between <strike> opening tag and closing tag.
strings.xml
1. StrikeThrough Using strike
2. Using Paint Flags – TextView StrikeThrough Example
Paint class provides
STRIKE_THRU_TEXT_FLAG
named flag. It creates strikethrough for TextView easily.
textview2.paintFlags = textview2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
textview2.text = "2. StrikeThrough Using Paint Flags"
textview2.setPaintFlags(textview2.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
textview2.setText("2. StrikeThrough Using Paint Flags");
3.1 SpannableString – TextView StrikeThrough Example
Applying StrikethroughSpan() with setSpan method of SpannableString, We can also create StrikeThrough.
val content1 = "3.1 StrikeThrough Using SpannableString"
val spannableString1 = SpannableString(content1)
spannableString1.setSpan(StrikethroughSpan(),0,content1.length,0)
textview31.text = spannableString1
SpannableString spannableString=new SpannableString("3.1 StrikeThrough Using SpannableString");
spannableString.setSpan(new StrikethroughSpan(),0,spannableString.length(), 0);
textview3.setText(spannableString);
3.2 Using SpannableString – TextView StrikeThrough Example
We can control strikethrough where to appear in a text. For that, provide start and endpoints of the text. Here I StrikeThrough the content “StrikeThrough” using 4 as the start point and 17 as the endpoint.
val content2 = "3.2 StrikeThrough Using SpannableString"
val spannableString2 = SpannableString(content2)
spannableString2.setSpan(StrikethroughSpan(),4,17,0)
textview32.text = spannableString2
SpannableString spannableString32=new SpannableString("3.2 StrikeThrough Using SpannableString");
//here strikethrough start point: 4, end point: 17
spannableString32.setSpan(new StrikethroughSpan(),4,17, 0);
textview32.setText(spannableString32);
4. Using shape drawable – Android TextView StrikeThrough XML
Using Shape drawable, create a horizontal line and put that line middle of your text.
strikethrough_shape.xml
put strikethrough_shape.xml as TextView background attribute value.
5. Using LayerList – Android TextView StrikeThrough XML
We can create a horizontal line using layerlist drawable also. Just like the above example, put this also as TextView’s background value.
strikethrough_layerlist
put strikethrough_layerlist.xml as TextView’s background value.
6. Using RelativeLayout and View – Android TextView Strikethrough XML example
RelativeLayout positions its element relative to each other. So let’s create a horizontal line using view and position it above-center of the TextView.
How To Remove TextView StrikeThrough
Use inv() method with Paint.STRIKE_THRU_TEXT_FLAG. Java users, use this ‘~’ symbol with Paint.STRIKE_THRU_TEXT_FLAG. Just like below
textview.paintFlags = textview.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
String html = "<u>Underline using Html.fromHtml()</u>";
textview.setText(Html.fromHtml(html));
But Html.fromHtml(resource : String) was deprecated in API 24. So now you can use HtmlCompat.fromHtml() method. It’s available in both android.support.v4.text.HtmlCompat, and androidx.core.text.HtmlCompat.
val html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>"
//1.1 underline textview using HtmlCompat.fromHtml() method
textview11.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)
String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>";
//underline textview using HtmlCompat.fromHtml() method
textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));
1.2 Above underline method in a direct way
This is for beginners. You can directly implement the code just like below.
textview12.text = HtmlCompat.fromHtml("<u>1.2 Underline using HtmlCompat.fromHtml()</u> ", HtmlCompat.FROM_HTML_MODE_LEGACY)
You can underline TextView using SpannableString and setSpan() method with the help of UnderlineSpan().
val content1 = "3.1 Underline using SpannableString"
val spannableString1 = SpannableString(content1)
spannableString1.setSpan(UnderlineSpan(),0,content1.length,0)
textview31.text = spannableString1
String content1 = "3.1 Underline using SpannableString";
SpannableString spannableString1 = new SpannableString(content1);
spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
textview31.setText(spannableString1);
3.2 Underline Using SpannableString
You can underline wherever you want in a word or sentence. Just Specify the start and endpoints.
val content2 = "3.2 Underline using SpannableString"
val spannableString2 = SpannableString(content2)
spannableString2.setSpan(UnderlineSpan(),4,13,0)
textview32.text = spannableString2
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true
strings.xml
<resources>
<string name="app_name">UnderlineTextView Ex</string>
<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
</resources>
Sometimes, we make our app using the code from youtube tutorials and blogs and may forget to change the package name at the start. Yes, this happens, most of the time.
We don’t want to display other website name or Youtube channel name to be as our package name, We want a package name that defines us. If you are searching for a tutorial about how to change or rename the Android app package name in Android Studio, then this post is for you.
In this post, I am going to discuss 3 methods that I am using and still working.
Method 2 – How to change full package name of project by creating new package
In this method, We are going to change package name “com.androidride.myapplication” to “info.xyz.yourapplication”
STEP 1
Right click on com.androidride.myapplication package and select Refactor->Move
STEP 2
Choose Move package “com.androidride.myapplication” to another package and click on OK.
STEP 3
Now you will get a warning dialog shows Multiple directories correspond to package com.androidride.myapplication
Click on Yes
STEP 4
Enter the new package name except the last level, For example. If you want to make package name as “info.xyz.yourapplication” then type “info.xyz” only, like above. Avoid the last part, here “yourapplication”.
STEP 5
Click YES for creating new package.
STEP 6
Click on Do Refactor. Now package name “com.androidride.myapplication” changes into “info.xyz.myapplication“.
STEP 7
Now we have to change the last package level name,
Right click on package name -> Refactor -> Rename
STEP 8
Click on Rename package
STEP 9
Rename “myapplication” in to “yourapplication”.
STEP 10
Click on “Do Refactor”
STEP 11
Use CTRL key and select each package related to old package name and delete. You can use DELETE key in keyboard or right click after selecting old packages and click on delete option from the menu.
STEP 12
Open build.gradle file, change applicationId and Click on sync now.
Package name successfully changed to “info.xyz.yourapplication“.
Method III – How to rename android app package name in Android Studio using existing package
This method is also same as the second method. Just like second, we change package name “com.androidride.myapplication” to “info.xyz.yourapplication“.
STEP 1
Right click on Java and select New -> Package
STEP 2
Next dialog box appears, choose …app\src\main\java as Destination Directory.
STEP 3
Enter your package name, here info.xyz.yourapplication
STEP 4
Now move old package files into new package. Here move files from “com.androidride.myapplication” to “info.xyz.yourapplication“. Just use CTRL key to select all files and drag it to new package.
Files moved.
STEP 5
Open AndroidManifest.xml and change package name into “info.xyz.yourapplication“
.
STEP 6
Open build.gradle (Module: app) file, change applicationId also. Change it to “info.xyz.yourapplication” and Click on Sync now.Now you might get errors. It is due to the R file import. There are two scenarios, we can do.
Remove R file import line from both files and check the error still exists. If not then you can delete old package files now
It’s done. You have successfully changed the package name.
Otherwise, If the error still exists, do the below steps.
STEP 7
Select R file import line just like above and press CTRL + SHIFT + R . Replace with new package name. Click on replace all.
STEP 8
Click on replace
STEP 9
Delete old package and related files
STEP 10
Build->Rebuild
Yes, the package name is changed.
Express your thoughts below and tell your friends about this post. Thank you.
Click Shift key twice or search icon at the top – right side corner of the Android Studio
Search “plugins“
Click on plugins item on the list
You can also get plugins window by File->Settings->Plugins
Now plugins window will appear, just click on “Browse repositories“
Search “Android Wifi ADB” plugin”
Select “Android WiFi ADB” from plugins list”
Install it.
The plugin will be downloaded.
Click “Restart Android Studio“.
Android Studio shows a notification Restart Android Studio to activate changes in plugins? Click “Yes“
Make sure that USB debugging is fine and successfully connected with the USB cable.
After the restart, just click the Android WiFi ADB icon that besides the run button like above.
Android Studio notifies with a message that your device is connected.
Disconnect your device, otherwise run dialog will show your device twice. one as USB device, other as WiFi device.
Click the run button and select your device in the run device dialog.
After selecting the device, it will continue to download through WiFi and install on your device.
Strategy NO:2 – How to run your app over WiFi using ADB commands
Sometimes, This method may difficult for you if you are a beginner. But we are just
connecting the device using the IP address
Install the app through ADB command.
Open Android Studio,
Click your terminal on Android Studio, You can also use the command prompt.
Type “adb devices” and Press Enter key – List the devices which are connected to system.
If your device is plugged with USB, then it will show it to you on the terminal.
Type “adb tcpip 5555” and Press Enter key.
Now you can disconnect your device.
Find the IP address of your smart device. You can find it by Settings-> About Phone -> Status -> IP address.
Now connect your device over wifi by running
“adb connect <IP address of your Android Device>:5555“
that’s all. your Android device successfully connected with computer.
Install apk – adb install “full location of apk”
adb install C:/app-debug.apk – here C:/app-debug.apk – full location of APK, I just placed the APK to C drive.
It’s a nice technique, but we are not saying that to leave USB cables forever. It’s needed for initial setup. If your pc and Android device restart again, Then you need to use USB cables again for reidentify the device.
Share your experiences with us and don’t forget to share.
In this example, you will learn how to open the calendar on button click in Android with an example. Here I use DatePickerDialog, not CalendarView. Beginners tend to use Calendar, that’s why I use that here.
//getting current day,month and year.
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
Calendar calendar = Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
int day=calendar.get(Calendar.DAY_OF_MONTH);
3. Initialize DatePickerDialog with the current date and show it. If you don’t and use 0 as day, month, and year. Then DatePickerDialog shows Feb month 1900.
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
}
}, myear, mMonth, mDay);
datePickerDialog.show();
4. Get day, month and year from DatePickerDialog onDateSet() method.
When you select a date in DatePickerDialog, onDateSet() method gives day, year in the as correct number specified in DatePickerDialog. But month value varies from 0 to 11. So just add 1 to month value to show the original month number.
Create Project – Open Calendar on Button click in Android Example
Let’s create a project that sets the date in EditText. When you click on Button, DatePickerDialog shows up, When you select a date, it sets on EditText.
Start a new Android Studio project
Application name: Open Calendar on Button Click in Android Example.
Conclusion
There are many occasions when you need a date from the user. Date of birth in sign up process, Ticket reservation, and date of an upcoming event just like that. It may not be user-friendly If the user needs to type it down. Android provides views for that, so users can easily pick it up. So I think if you are making an app like that, this post might have helped you. If you like this tutorial, please share it.
In this tutorial, you’ll learn four ways to make an Android TextView bold. You can easily adapt the code and use it in your project as needed. Let’s get started!
String html="This is TEXTVIEW 3";
textview3.setText(Html.fromHtml(html));
Html.fromHtml(String source) was deprecated in API level 24. Use androidx.core.text.HtmlCompat instead. For using HtmlCompat, you need to include dependency in your project.
implementation 'androidx.core:core:1.0.1'
If you got Manifest merger failed error, then add below code in gradle.properties.
String html="This is TEXTVIEW 3";
textview3.setText(HtmlCompat.fromHtml(html,Typeface.BOLD));
HtmlCompat.FROM_HTML_MODE_LEGACY – It just adds two newline character between block level elements.
Way 4 – Make Android TextView Bold using separate style
In this example, we create a separate style resource and set it to our TextView. The advantage of this technique – you can use this style for many TextViews. Just specifying style attribute.
Step 1
Create a separate style resource named “boldStyle”, add “android:textStyle” as item and provide value “bold”.
Step 2
Set style to TextView using style attribute.
Let’s create an Android app with these examples. Open your Android Studio,
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true
colors.xml
#008577#00574B#D81B60
strings.xml
TextView Bold Example
styles.xml
activity_main.xml
MainActivity.kt
package com.example.androidride.textviewbold_kotlin
import android.graphics.Typeface
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Make textview bold - programmatically
textview2.setTypeface(null,Typeface.BOLD)
textview2.text= "TEXTVIEW 2"
//Using fromHtml() method
val html = "This is TEXTVIEW 3"
textview3.text = HtmlCompat.fromHtml(html,HtmlCompat.FROM_HTML_MODE_LEGACY)
}
}
In this post, you will learn how to convert Java class to Kotlin in Android Studio. Google announced Kotlin as an official language for Android Development. When comparing Java with Kotlin, It has lots of advantages. But I am not going to talk about its advantages here.
If you are from Java and want to step into Kotlin world, But don’t know how to write your code in Kotlin. Don’t worry, Kotlin plugin helps to convert Java code to Kotlin in Android Studio. Just type your code in Java then use below steps
This is not 100% perfect, the Best way is to learn Kotlin on your own. But for beginners, This will help a lot to move forward with Kotlin.
If you are using below Android Studio 3.0, You must install Kotlin plugin. Then only below steps work. So go to this tutorial and install Kotlin plugin in Android Studio. Otherwise, Just read on.
Open any project in Android Studio, Here I have opened the HelloWorld App.
Choose Code-> Convert Java File to Kotlin File or you can also use keyboard shortcut Ctrl + ALT + Shift + K.
Now plugin starts its job and your .java files will convert to .kt files in the src folder.
You will get a notification says “Kotlin not configured”. Just click on Configure.
If you don’t get the configure option, then you need to go
Tools-> Kotlin -> Configure Kotlin in Project
Select the latest Kotlin compiler and runtime version, and click OK.
After gradle configuration,
ext.kotlin_version stores Kotlin version and uses in various spots.
Added a dependency for Kotlin plugin
Kotlin plugin added
Kotlin standard library dependency added.
you don’t have to convert each java file one by one for a big project, you can convert the whole package using the above method.
The plugin also converts automatically if you paste java code into Kotlin file.
JetBrains team does not stop making java to Kotlin offline tool, they also provide an online tool.
Convert Java code to Kotlin – online.
Go to this URL “https://try.kotlinlang.org/” and click on “Convert from Java”
how to convert java class to kotlin online
Just paste your java code in the left section and click on “convert to Kotlin” shown on the bottom of the box. Now Kotlin code will appear on the right section.
Conclusion
Kotlin has become one of the fastest growing languages after Google has selected it as an official language for Android Development. Many of the business giants are also started making big projects in Kotlin. If you are a beginner in Kotlin and know how to code in Java. Don’t worry you can convert it to Kotlin using the Kotlin plugin. Android Studio makes the process more simple, so you can accomplish migration in a few seconds. For the beginning days, It assists you well to understand the basic structure of Kotlin. I assume this post might have helped you and If you like this post, please share it. Any other ways to convert, feel free to comment here.
There may be occasions when you want to show a webpage to your users such as Terms and conditions, app manual or your website and so on.
In a traditional way, we can send users to an external web browser but there is no guarantee that users would come back. So that’s one of the main reasons Android introduced a widget named WebView.
As the name suggests it helps to show or view online and offline web pages in our app. It’s available in android.webkit package and has abilities in history management, zooming, javascript, and CSS rendering.
So you can load the webpage easily in your app, webview will take care of it. It’s not a browser because it lacks navigational toolbar like features.
From the beginning to now, WebView has grown a lot. Let’s check how it implemented in Android.
WebView to Android System Webview – implementation history
WebView to Android System WebView -WebView implementation history
WebView was added in API level 1. It renders web pages using Webkit engine, which behind Apple’s Safari browser. Actually, WebKit makes an environment or views for the webpage to display on the app.
In Android 4.4, For better performance, Google decided to change webview rendering from stock webview to google’s chromium or blink.
Lots of bugs and fixes through os update, that made long time vulnerable. So Android engineers innovated a separate Android System Webview app that can install and update through Google’s app market Play store with next release “Lolipop”.
That made easy fixes in less time.
In Android 7.0, there is no need to enable Android System Webview app, Chrome will take care of webview. if it is disabled or uninstalled already, the system will use android system webview.
If both of them get disabled, webview will use stock Webkit engine and take care of your valuable web pages.
How to add WebView to your layout?
Webview can easily be added to your layout as any other view. You can just drag and drop webview or write code for that just like below
For Kotlin users, I am using Android studio 3.1.2 and it uses Kotlin Android Extensions plugin by default. So there is no need to call findviewByid and cast. just use the id of the widget and call the methods.
Okay… Let’s start with our first example – Using the loadUrl() method.
Load Url – WebView Android Example In Kotlin & Java
android webview loadurl example
We can easily load a webpage in webview using loadUrl() method. Just put your URL as a string, Before that, we must provide Internet permission in AndroidManifest.xml.
create a webview app in android with below code
package com.androidride.webviewloadurlex
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//loads androidride homepage to webview, webview: id of webview
webview.loadUrl("https://www.androidride.com")
}
}
This is enough to open your links in webview. It internally calls, shouldOverrideUrlLoading() method and it returns false. False means redirect or clicking on a link opens in the same webview, True will abort the operation.
How to open link in the external browser using Android WebView
Sometimes You need to open your website links in webview and other links in external browsers. Then you can use the below sample code.
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (Uri.parse(url).getHost().equals("https://www.example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
But shouldOverrideUrlLoading (WebView view, String url) was deprecated in API level 24. So if you are planning to make an application for Nougat or above, then you can use
public boolean shouldOverrideUrlLoading (WebView view,WebResourceRequest request)
To open links in WebView in All devices use both shouldOverrideUrlLoading() methods just like
webview.webViewClient = object : WebViewClient()
{
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
{
if(Uri.parse(url).host=="www.example.com")
{
return false
}
val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url))
startActivity(intent)
return true
}
@RequiresApi(Build.VERSION_CODES.N)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
{
val url=request?.url.toString()
if(Uri.parse(url).host=="www.example.com")
{
return false
}
val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent)
return true
}
}
@RequiresApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
String url=request.getUrl().toString();
if (Uri.parse(url).getHost().equals("https://www.example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (Uri.parse(url).getHost().equals("https://www.example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
How To Play YouTube Video In WebView By Enabling JavaScript In Android
Let’s open youtube in our webview.
Use our first example, and replace URL in loadUrl with “https://www.youtube.com” and run.
webview.loadUrl("https://www.youtube.com");
You may see these type of actions:
Youtube shows a progress bar loading.
Bowser says Please enable JavaScript in your browser.
This is because of JavaScript. If you are a web developer, you already know the importance of javascript. If you don’t, Javascript is a client-side programming language, it helps us to provide validation, animations and popups and so on.
By default, Javascript is disabled on your browser. we can easily enable it by simple lines of code.
how to enable javascript in android webview
//enables javascript in webview
webview.settings.javaScriptEnabled = true
//enables javascript in webview
webview.getSettings().setJavaScriptEnabled(true);
Now you can start watching youtube videos in your webview.
Android WebView local file example
android webview local file example
In this example, you will learn how to show a local HTML file in webview. We have already created a webpage for you. You can use that for a sample.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Android webview local file ex - androidride</title>
<style type="text/css">
h1
{
border:2px solid #707cff;
padding:5px;
color:#707cff;
margin-top:120px;
text-align:center;
background-color:white;
}
p
{
text-align:center;
}
body
{
background-color:#e0e0e0;
}
</style>
</head>
<body>
<h1>ANDROIDRIDE</h1>
<p>
This is a <strong>local html file</strong> loaded from <strong>assets</strong> folder
</p>
</body>
</html>
This is a local html file loaded from assets folder
Just make an assets folder in your project, Right click on app->New->Folder->Assets Folder. Now a dialog appears to change the location of assets folder. Leave it and Click Finish.
Place demo.html into assets folder and use below code
package com.example.androidride.webviewlocalfileex
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//loads local html file
webview.loadUrl("file:///android_asset/demo.html")
}
}
In URL, use android_asset not android_assets, yes, there is no ‘s’ at the end.
webview.loadUrl(“file:///android_res/mipmap/ic_launcher”)
There is no need for the file extension, but it won’t be a problem if you add it.
content://URLs pointing content provider.
ERR_UNKNOWN_URL_SCHEME in Android WebView – Fixed.
err_unknown_url_scheme in android webview fixed
In this example, You will learn how to solve ERR_UNKNOWN_URL_SCHEME in Android WebView. This type of error happens when WebView deals with UNKNOWN URL SCHEME links. Before that learn some basics.
What is URL SHEME?
The URL scheme is something before the colon in the URL. actually, it’s the protocol describes how to access the resource.
WebView knows how to deal with HTTP, HTTPS, and file Schemes, but they don’t know what to do when these type of schemes come. ‘tel:’, ‘sms:’, and ‘mailto:’ and others.
So we have to tell webview to how to deal with those schemes in shouldOverrideUrlLoading() method. In this example, we are going to use ‘tel:’, ‘sms:’, ‘mailto:’, and ‘geo:’ links. When you click on them, each link will get opened with appropriate apps installed on your Android device.
demo.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Error Unknown URL scheme fixed - androidride</title>
</head>
<body>
<a href='tel:99999999999'>Click here to call</a><br><br>
<a href='sms:99999999999'>Click here to message</a><br><br>
<a href='mailto:example@mail.com'>Click here to mail</a><br><br>
<a href='geo:51.5074,0.1278'>Click here to show location</a><br><br>
</body>
</html>
If it’s a network URL, WebView force the links to open in WebView,otherwise find a best option from Android System.
Create your webview app with the above code or you can download our example.
WebView loadData() example in Android
In this Android WebView example, we will show you how to render HTML code in Android WebView. It’s simple, Android API provides a method called loadData().
loadData() method needs 3 contents.
String htmlData: This is our html content.
String mimeType: here we use “text/html”.
String encoding: most of the time, base64 or UTF-8.
It works with data,http and https schemes.
If you use other schemes, webview can’t access content due to javascript same origin policy.
You should use loadDataWithBaseURL(), if you want to use other schemes.
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val html="
In this example, you will learn how to work with loadDataWithBaseURL() example. When you want to fetch an image from the assets folder using loadData() method. JavaScript origin policy restricts the access to content.
loadDataWithBaseURL() avoids this problem by specifying BaseURL. Using the Base URL, system resolve relative URLs in HTML content.
loadDataWithBaseURL() needs
String baseURL: This URL is used to resolve relatvie URLs.
String data: Html content that you want to show.
String mimeType: mimeType of HTML data
String encoding: encoding of html data
String historyURL: This URL loads when you navigate back in webview
In this example, I am going to use the same loadData() code but just want to add image ‘ic_launcher’ from the mipmap folder.
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val html="
In this android webview example, you will learn how to download a file using WebView and DownloadManager. Using DownloadManager, we can reduce code and leave the stress to DownloadManager. We also show AlertDialog for Download notification.
public class MainActivity extends AppCompatActivity
{
private static final String TAG="AndroidRide";
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview=(WebView)findViewById(R.id.webview);
webview.loadUrl("https://www.google.com");
webview.setWebViewClient(new WebViewClient());
webview.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(final String url, final String userAgent, String contentDisposition, String mimetype, long contentLength)
{
//Checking runtime permission for devices above Marshmallow.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
downloadDialog(url,userAgent,contentDisposition,mimetype);
} else {
Log.v(TAG,"Permission is revoked");
//requesting permissions.
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
else {
//Code for devices below API 23 or Marshmallow
Log.v(TAG,"Permission is granted");
downloadDialog(url,userAgent,contentDisposition,mimetype);
}
}
});
}
public void downloadDialog(final String url,final String userAgent,String contentDisposition,String mimetype)
{
//getting filename from url.
final String filename = URLUtil.guessFileName(url,contentDisposition,mimetype);
//alertdialog
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
//title of alertdialog
builder.setTitle("Download");
//message of alertdialog
builder.setMessage("Do you want to save " +filename);
//if Yes button clicks.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//DownloadManager.Request created with url.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//cookie
String cookie=CookieManager.getInstance().getCookie(url);
//Add cookie and User-Agent to request
request.addRequestHeader("Cookie",cookie);
request.addRequestHeader("User-Agent",userAgent);
//file scanned by MediaScannar
request.allowScanningByMediaScanner();
//Download is visible and its progress, after completion too.
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//DownloadManager created
DownloadManager downloadManager=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
//Saving files in Download folder
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
//download enqued
downloadManager.enqueue(request);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
//cancel the dialog if Cancel clicks
dialog.cancel();
}
});
//alertdialog shows.
builder.create().show();
}
}
How To Run JavScript In Android WebView
how to run javascript in android webview
I already said JavaScript has an important role in the web world. In Android, we can also make use of JavaScript by sending data to Javascript from Android and vice versa. But it also raises security issues too. If you are using any third-party code, make sure it’s not vulnerable to users security.
Android API provides a number of methods and classes to achieve a super web app. I have categorized them
JavaScript calling Kotlin/Java
addJavascriptInterface()
WebMessagePort – (6.0)
Kotlin/Java calling JavaScript
loadUrl()
evaluateJavascript() – (4.4)
WebMessage – (6.0)
The numbers shown in the brackets means the starting API. We are not going to discuss WebMessagePort and WebMessage here. That will be updated later.
webview addJavascriptInterface example in android
webview addjavascriptinterface example in android
In this addJavascriptInterface example, we send a message from a local HTML webpage to Android and show it through a toast.
JavaScript can access methods in API level Build.VERSION_CODES.JELLY_BEAN_MR1 and above, if they are
defined as public
annotated with JavascriptInterface
sample.html
WebView addJavascriptInterface Example
Web To Android
MainActivity.kt
class MainActivity : AppCompatActivity()
{
@SuppressLint( "SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//webview loads sample html
webview.loadUrl("file:///android_asset/sample.html")
//enables javascript in webview
webview.settings.javaScriptEnabled = true
//injecting java object
webview.addJavascriptInterface(JavascriptInterface(),"javascript_object")
}
private inner class JavascriptInterface
{
@android.webkit.JavascriptInterface
fun showToast(text: String?)
{
//toasting the text
Toast.makeText(this@MainActivity,text,Toast.LENGTH_SHORT).show()
}
}
override fun onDestroy()
{
//removes the java object from webview
webview.removeJavascriptInterface("javascript_object")
super.onDestroy()
}
}
public class MainActivity extends AppCompatActivity
{
WebView webview;
@SuppressLint("SetJavascriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get webview
webview=(WebView)findViewById(R.id.webview);
//webview loads sample html
webview.loadUrl("file:///android_asset/sample.html");
//enables javascript in webview
webview.getSettings().setJavaScriptEnabled(true);
//injecting java object in webview
webview.addJavascriptInterface(new JavascriptInterface(),"javascript_object");
}
public class JavascriptInterface
{
@android.webkit.JavascriptInterface
public void showToast(String text)
{
//toasting text
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy()
{
//removes java object from webview
webview.removeJavascriptInterface("javascript_object");
super.onDestroy();
}
}
how above code works?
JavaScript enabled.
Inject java object into webpage using addJavascriptInterface() method. It needs
Java class object: The java class object which inject into webview
String name: The name used to access java methods from JavaScript
It’s better to remove java object from webview after the use
WebView evaluateJavascript example in Android
Let’s call javascript from Java. In this example, we receive the text from edittext and send it to the local HTML page. Use loadUrl() for below 4.4 and evaluateJavascript() works with KitKat and above.
sample.html
Android Javascript Ex
WebView
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//loads sample html
webview.loadUrl("file:///android_asset/sample.html")
//enables javascript in webview
webview.settings.javaScriptEnabled = true
}
fun sendMessage(view: View?)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
//calls when version code greater than or equal to KITKAT
webview.evaluateJavascript("show(\"" + edittext.getText() + "\")",null)
}
else
{
webview.loadUrl("javascript:show(\"" + edittext.getText() + "\")")
}
}
}
Add INTERNET and WRITE_EXTERNAL_STORAGE permission in AndroidManifest.xml
AndroidManifest.xml
android:windowSoftInputMode=”stateAlwaysHidden|adjustNothing” – it helps by without adjusting our bottom bar layout and disable the focus in EditText while startup.
android:background=”?android:selectableItemBackground” – makes transparent
I have used vector asset icons, you can also access them by right clicking on res->New->Vector Asset->Click on clip Art and select your icons, you can change color and size. Click OK and Next.
Step 9
custom_progress.xml
Step 10
This browser has a simple home page, for that, we have to add local HTML file in the assets folder.
package com.example.androidride.webviewbrowser;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Patterns;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import android.view.KeyEvent;
public class MainActivity extends AppCompatActivity
{
private Toolbar toolbar;
private EditText edittext;
private WebView webview;
//private ImageView imageview;
private String Share_url,Title_url;
private ProgressBar progressbar;
String filename,directoryName;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialise();
webview.loadUrl("file:///android_asset/demo.html");
setSupportActionBar(toolbar);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient()
{
@Override
public void onProgressChanged(WebView view, int newProgress) {
progressbar.setProgress(newProgress);
super.onProgressChanged(view, newProgress);
if(newProgress==100)
{
progressbar.setVisibility(View.GONE);
}
}
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
//set favicon to imageview
//imageview.setImageBitmap(icon);
}
});
webview.setWebViewClient(new WebViewClient()
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progressbar.setVisibility(View.VISIBLE);
if(!"file:///android_asset/demo.html".equals(url))
{
edittext.setText(url);
}
else
{
edittext.setText("");
}
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view,String url)
{
Share_url=url;
super.onPageFinished(view,url);
}
});
webview.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(final String url, final String userAgent, String contentDisposition, String mimetype, long contentLength)
{
//checking runtime permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
downloadDialog(url,userAgent,contentDisposition,mimetype);
} else {
//requesting permissions
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
else {
//Code for devices below API 23 or Marshmallow
downloadDialog(url,userAgent,contentDisposition,mimetype);
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode==KeyEvent.KEYCODE_BACK)&&this.webview.canGoBack())
{
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void goBack(View view)
{
if(webview.canGoBack())
webview.goBack();
}
public void goForward(View view)
{
if(webview.canGoForward())
webview.goForward();
}
public void goHome(View view)
{
webview.loadUrl("file:///android_asset/demo.html");
}
public void refresh(View view)
{
webview.reload();
}
public void share(View view)
{
Intent shareIntent=new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,Share_url);
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"URL");
startActivity(Intent.createChooser(shareIntent,"Share with your friends"));
}
public void go(View view)
{
String text=edittext.getText().toString();
searchOrLoad(text);
}
void searchOrLoad(String txt)
{
if(Patterns.WEB_URL.matcher(txt.toLowerCase()).matches())
{
if(txt.contains("http://")||txt.contains("https://"))
{
webview.loadUrl(txt);
}
else
{
webview.loadUrl("http://"+txt);
}
}
else
{
webview.loadUrl("https://www.google.com/search?q="+txt);
}
hideKeyboard();
}
private void initialise()
{
toolbar=(Toolbar)findViewById(R.id.toolbar);
edittext=(EditText)findViewById(R.id.search_load_edit_text);
webview=(WebView)findViewById(R.id.webview);
progressbar=(ProgressBar)findViewById(R.id.progressbar);
//imageview=(ImageView)findViewById(R.id.toolbar_search_imageview_favicon);
}
public void hideKeyboard()
{
InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
View view=getCurrentFocus();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
public void downloadDialog(final String url,final String userAgent,String contentDisposition,String mimetype)
{
//file name
final String filename = URLUtil.guessFileName(url,contentDisposition,mimetype);
//Creates AlertDialog.
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
//title of Dialog
builder.setTitle("Download");
//Message of Dialog.
builder.setMessage("Do you want to save " +filename);
//if YES button clicks
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//DownloadManager.Request created with url.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//cookie
String cookie=CookieManager.getInstance().getCookie(url);
//Add cookie and User-Agent to request
request.addRequestHeader("Cookie",cookie);
request.addRequestHeader("User-Agent",userAgent);
//file scanned by MediaScannar
request.allowScanningByMediaScanner();
//Download is visible and its progress, after completion too.
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//DownloadManager created
DownloadManager downloadManager=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
//Saving file in Download folder
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
//download enqued
downloadManager.enqueue(request);
}
});
//If Cancel button clicks
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
//cancel the dialog if Cancel clicks
dialog.cancel();
}
});
//Shows alertdialog
builder.create().show();
}
}
Hey… Thanks for scrolling. If you find anything useful in this post, please share it.
Conclusion
WebView has an important role in Android programming. With a few lines of code, beginners can also easily load web pages in their app. You have learned to download the file and run javascript using Android WebView. I am sure that these examples make you better dealing with WebView. This is a small guide about WebView. You can also find more information from below links.