I developed a website for my entreprisee and I work almost exclusively with PHP
So the Java language (and android studio) is a really new for me. Despite this I have to create an APK to use the website (in order to block the android home on this site)
But when I turn the screen, the webview displays the homepage rather than the current page.
I did some research and I integrated what I saw here: Android - Preventing WebView reload on Rotate
But that does not work and I do not understand why I always come back on "Google.com"
MainActivity.java
package eu.test.chrome;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
LoadWeb();
progressBar.setMax(100);
progressBar.setProgress(1);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
public void onPageFinished(WebView view, String url) {
//Don't show ProgressBar
progressBar.setVisibility(View.GONE);
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
/* I integrated what I saw here: https://stackoverflow.com/questions/12131025/android-preventing-webview-reload-on-rotate but that does not work
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}*/
public void LoadWeb() {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.loadUrl("https://www.google.com/");
swipe.setRefreshing(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rel_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ProgressBar
android:id="#+id/awv_progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="26dp"
android:indeterminate="true" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="eu.test.chrome">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:hardwareAccelerated="false"
android:configChanges="orientation|screenSize"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In Order to Load the Url Before Rotation, you need to make some additions.
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
ProgressBar progressBar;
private final String CACHE_URL_KEY = "CACHE_URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
LoadWeb(savedInstanceState);
progressBar.setMax(100);
progressBar.setProgress(1);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
public void onPageFinished(WebView view, String url) {
//Don't show ProgressBar
progressBar.setVisibility(View.GONE);
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
outState.putString(CACHE_URL_KEY,webView.getUrl());
super.onSaveInstanceState(outState);
}
public void LoadWeb(Bundle savedInstanceState) {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
if (savedInstanceState != null) {
String savedUrl = savedInstanceState.getString(CACHE_URL_KEY);
webView.loadUrl(savedUrl);
}else {
webView.loadUrl("https://www.google.com/");
}
swipe.setRefreshing(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
}
These are the Steps Made:
You need to Create a Key to identify the Saved URL
private final String CACHE_URL_KEY = "CACHE_URL";
You need to save the URL Each Time you rotate
#Override
protected void onSaveInstanceState(Bundle outState ) {
outState.putString(CACHE_URL_KEY,webView.getUrl());
super.onSaveInstanceState(outState);
}
You Need to Check if There is a Rotation or not. If yes, savedInstanceState won't be null therefore retrieve the Url and load it.
Else Load Default page
if (savedInstanceState != null) {
String savedUrl = savedInstanceState.getString(CACHE_URL_KEY);
webView.loadUrl(savedUrl);
}else {
webView.loadUrl("https://www.google.com/");
}
Also, Pass the saved state to LoadWeb method
Try this
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v4.widget.SwipeRefreshLayout;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Main2Activity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
ProgressBar progressBar;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
LoadWeb();
progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
progressBar.setMax(100);
progressBar.setProgress(1);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("https://stackoverflow.com/questions/47885592/how-to-add-a-progress-loading-bar-in-webview/47885692#47885692");
}
public void onLoadResource(WebView view, String url) { //Doesn't work
// swipe.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
//Hide the SwipeReefreshLayout
progressBar.setVisibility(View.GONE);
swipe.setRefreshing(false);
}
});
}
public void LoadWeb() {
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.loadUrl("http://dev.ncryptedprojects.com/bistrostays_v3/");
swipe.setRefreshing(true);
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
}
and in your manifest file
<activity android:name=".MainActivity"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Create Method in Android like :
#JavascriptInterface
public boolean CallByMobApp(){
return true;
}
Create Calling function in JavaScript :
$(window).load(function () {
IsCallByMobileApp = false;
try {
IsCallByMobileApp = app.CallByMobApp();/*Is call by android app*/
} catch (e) {
IsCallByMobileApp = false;
}
}
According to this method you can manage which page to be open.
You call the method LoadWeb each time. You need to check if savedInstanceState == null then call LoadWeb. If savedInstanceState != null then don't call LoadWeb
Related
My Code :
My Adapter
#Override
public void onBindViewHolder(#NonNull SliderAdapter.SliderHolder holder, int position) {
final HomePage.ContentList item = homePageList.get(position);
SliderHolder viewHolder = (SliderHolder) holder;
viewHolder.txt_category.setText(item.getCategoryName());
viewHolder.title_item_list_pager.setText(item.getTitle());
if (item.getImage() != null)
Glide.with(holder.itemView).load(item.getImage()).into(viewHolder.img);
Log.d("TEST103-2", "PV");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), NewsDetail.class);
intent.putExtra("newsdetail",homePageList.get(position).getExternalUrl());
v.getContext().startActivity(intent);
}
});
}
news detail class
package com.platin.android;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class NewsDetail extends AppCompatActivity {
WebView newsdetail;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
newsdetail = findViewById(R.id.newsdetail);
newsdetail.getSettings().setJavaScriptEnabled(true);
newsdetail.loadUrl(getIntent().getStringExtra("newsdetail"));
}
}
I want to show my externalurl link coming from api in webview in my application.
When I click for detail, it opens on google chrome. but I want it to show in application.
set setWebViewClient in your WebView also you can enable javaScript
webView.loadUrl(getIntent().getStringExtra(LINK));
webView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
and Clint is:
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
When I tried to access (file:///sdcard/) using mobile browsers (ex. Firefox, Opera ..etc). It shows me an index page for the SDCard (see the screenshot).
However, when I access the same url using a webview and give it a storage permission and does not show the Index page. My code is below:
package com.example.webbrowser;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
class NetworkState {
public static boolean connectionAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() !=null;
}
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
}
public class MainActivity extends AppCompatActivity {
WebView webView;
EditText editText;
ProgressBar progressBar;
Button back, forward, stop, refresh, homeButton;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.web_address_edit_text);
back = (Button) findViewById(R.id.back_arrow);
forward = (Button) findViewById(R.id.forward_arrow);
stop = (Button) findViewById(R.id.stop);
goButton = (Button)findViewById(R.id.go_button);
refresh = (Button) findViewById(R.id.refresh);
homeButton = (Button) findViewById(R.id.home);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setMax(100);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) findViewById(R.id.web_view);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setBackgroundColor(Color.WHITE);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
if (newProgress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
if (newProgress == 100) {
progressBar.setVisibility(ProgressBar.GONE);
}else{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
}
});
}
}
public void go_button(View view) {
try {
if(!NetworkState.connectionAvailable(MainActivity.this)){
Toast.makeText(MainActivity.this, "Check connection", Toast.LENGTH_SHORT).show();
}else {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
webView.loadUrl(editText.getText().toString());
editText.setText("");
}
}catch (Exception e) {
e.printStackTrace();
}
}
public void home_button(View view) {
webView.loadUrl("https://google.com");
}
public void refresh_button(View view) {
webView.reload();
}
public void stop_button(View view) {
webView.stopLoading();
}
public void forward_button(View view) {
if (webView.canGoForward()) {
webView.goForward();
}
}
public void back_button(View view) {
if (webView.canGoBack()) {
webView.goBack();
}
}
}
Android mainifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webbrowser">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.WebBrowser">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Any help ?
I am building an Android app and I am newbie.
I am not able to make calls by clicking a button inside android webview app
Here is my code:
Mainactivity
package pk.gogobazar.gogobazarapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webView;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
public String url ="https://gogobazar.pk/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
webView.setWebViewClient(new xWebViewClient());
webView.setWebChromeClient(new WebChromeClient()
{
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (requestCode == REQUEST_SELECT_FILE)
{
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
else if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Android Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pk.gogobazar.gogobazarapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am new and still learning basics. Please help me to allow the phone calls in webview on this activity. So when someone clicks on phone number it should call, thanks.
This is How it works for me:
package com.example.myapplication;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
private static final String TEL_PREFIX = "tel:";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.webview);
wv.setWebViewClient(new CustomWebViewClient());
wv.loadUrl("https://google.pk");
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url) {
if(url.startsWith(TEL_PREFIX)) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
}
First you would need to bind your javascript code to your android code, this guide demonstrates how to do that. Then in your javascript, you could add a listener to your button that invokes a Java method.
Second, you need to integrate a calling solution into your app this guide explains what options you have and how you can implement them.
Once you implemented the calling solution, you could simply make a call from the Java method that you intend to invoke from your javascript.
I'm receiving an exception that equals null when attempting to create a new activity using Intent. Basically my program terminates when I try to create this new Activity i.e. switch the screen the user sees to one with an animated treasure box (png files from xml, which works when they are run from the MainActivity).
Here is a picture from Android Studio of the error I am receiving:
I'm developing a Vuzix M100 application on a device running vr4.0.4.
Here are the two activities I am running:
MainActivity.java
package com.rit.se.treasurehuntvuz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
try {
Intent showTreasureIntent = new Intent(this, ShowTreasureActivity.class);
startActivity(showTreasureIntent);
}
catch(Exception exception) {
Log.e("MainActivity", exception.getMessage());
}
}
}
ShowTreasureActivity.java
package com.rit.se.treasurehuntvuz;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
public class ShowTreasureActivity extends AppCompatActivity {
private ImageView treasureImage;
private AnimationDrawable treasureAnimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showtreasure);
treasureImage = (ImageView)findViewById(R.id.treasureAnimationView);
treasureImage.setBackgroundResource(R.drawable.anim_treasure);
treasureAnimation = (AnimationDrawable) treasureImage.getBackground();
treasureAnimation.setOneShot(true);
}
#Override
public void onWindowFocusChanged (boolean hasFocus)
{
treasureAnimation.start();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
}
}
Thanks to #Joel Duggan, it turned out I was lacking an entry in the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rit.se.treasurehuntvuz">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ShowTreasureActivity">
</activity>
</application>
</manifest>
Hello my App crash if I try to open my AddIP.class fragment
My error code says:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity$AddIP}: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.kwietzorek.fulcrumwebview" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity$AddIP"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
MainActivity.java
package de.kwietzorek.fulcrumwebview;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity {
String selected;
Spinner spinner;
WebView myWebView;
ArrayList<String> server_name_list = null;
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(this, AddIP.class);
this.startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//WebView
myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
//JavaScript enable
webSettings.setJavaScriptEnabled(true);
//Server name spinner
if (server_name_list != null) {
spinner = (Spinner) findViewById(R.id.server_spinner);
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
server_adapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
//WebView Client
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
public class AddIP extends Fragment {
Button btn_back, btn_add;
EditText server_ip, server_name;
String new_server_ip, new_server_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ip);
server_ip = (EditText) findViewById(R.id.edit_server_address);
server_name = (EditText) findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*new_server_ip = server_ip.getText().toString();
MainActivity.server_array_ip.add(new_server_ip);*/
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
}
}
}
Add this method to your faragment :
public AddIP() {
}
in some situation you need an empty constructor method for your fragment