I have been having a issue with a webview backbutton. I've never had this issue before regarding webview backbutton.
When I push the back button the logcat gives me the following error:
12-05 23:56:23.264: W/KeyCharacterMap(3743): Load KCM of non-default device may incur unexpected result
12-05 23:56:23.264: W/UnimplementedWebViewApi(3743): Unimplemented WebView method onKeyDown called from: android.webkit.WebView.onKeyDown(WebView.java:2323)
I've never seen this error before. Does anyone have a idea on what could be causing this?
Code:
package org.development;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class ImagenesActivity extends Activity {
ListView list;
Intent intent;
TextView toma_foto;
Button button_foto;
ImageAdapter adapter;
private WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagenesactivity);
toma_foto = (TextView) findViewById(R.id.toma_foto);
button_foto = (Button) findViewById(R.id.button_foto);
list=(ListView)findViewById(R.id.list);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);
mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new WebViewClient());
mWebView.clearCache(true);
mWebView.loadUrl("about:blank");
mWebView.clearView();
mWebView.loadUrl("http://mysite23.com/activity");
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
//view.loadUrl("javascript:document.getElementsByClassName('elgg-page-header').style.visibility='hidden';alert('testing');");
}
});
File file = new File(Environment.getExternalStorageDirectory() + "/genx/");
String[] filas = file.list();
if(filas==null)
filas = new String[0];
adapter=new ImageAdapter(this, filas);
list.setAdapter(adapter);
}
public void foto (View view){
/**We send to the camera Activity*/
//Intent j = new Intent(this, CameraActivity.class);
//startActivity(j);
//finish();
mWebView.loadUrl("about:blank");
mWebView.clearView();
mWebView.loadUrl("http://mysite23.com/activity");
}
public class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack() == true) {
mWebView.goBack();
} else {
ImagenesActivity.super.onBackPressed(); //Replace MyActivity With the name of your activity.
}
}
}
Related
I'm trying to create an APP from a Website. I've tried WebView in Android Studio [JAVA]. It worked fine with some minor issues. Now I want to implement Real time Pop up Notification in this App. But I don't know how to do it.
API of this Website:
https://api.v2.just.edu.bd/api/notices?page=null&ref=null&tag=&search=&limit=20
This is the code in main.java
package com.example.just;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView=(WebView) findViewById(R.id.webview);
mywebView.setWebViewClient(new WebViewClient());
mywebView.loadUrl("https://just.edu.bd/");
WebSettings webSettings=mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
public class mywebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view,url,favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view,String url){
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
}
I trying add webview in fragment1.java. The problem is the code runs but for every website it shows me a white screen, no crashing or error messages. This how it looks before add WebView:
package com.example.bottomnavigationview;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1,container,false);
return rootView;
}
}
And after:
package com.example.bottomnavigationview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1,container,false);
return rootView;
}
public class MainActivity extends AppCompatActivity {
String websiteURL = "https://www.example.com"; // sets web url
private WebView webview;
SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
{
//if there is no internet do this
setContentView(R.layout.activity_main);
//Toast.makeText(this,"No Internet Connection, Chris",Toast.LENGTH_LONG).show();
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("No internet connection available")
.setMessage("Please Check you're Mobile data or Wifi network.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
//.setNegativeButton("No", null)
.show();
}
else
{
//Webview stuff
webview = findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl(websiteURL);
webview.setWebViewClient(new WebViewClientDemo());
}
//Swipe to refresh functionality
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webview.reload();
}
}
);
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mySwipeRefreshLayout.setRefreshing(false);
}
}
//set back button functionality
#Override
public void onBackPressed() { //if user presses the back button do this
if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back
webview.goBack(); //go back in webview
} else { //do this if the webview cannot go back any further
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("EXIT")
.setMessage("Are you sure. You want to close this app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}
I think it needs to be put in some other way. Can somebody help? Because page in app don't downloading.***************************************************************************
follow this code snippet.
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
webView.setWebViewClient(new WebViewClient());
webView.loadDataWithBaseURL(null, YOUR_URL, "text/html", "utf-8", null);
here, webView will be replaced with your view object.
Note: addJavascriptInterface is optional. It will be used in the case when you want a callback from webChromeClient. also, for more details about addJavascriptInterface, you can refer to https://stackoverflow.com/a/11572941/8237887
This is a test app using simple android webview function. But I encountered fatal error in below when I pressed back button to go back to previous web page;
"java.lang.NullPointerException: Attempt to invoke virtual method
'boolean android.webkit.WebView.canGoBack()' on a null object
reference"
There are main page (MainActivity.java) and Web view page (WebviewPage.java).
I tried to fix this error through googling over and over ... but I couldn't.
Thanks in advance.
MainActivity.java
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);}
public void onClick(View view) {
Intent intent1 = new Intent (this, WebViewPage.class);
intent1.putExtra("name","https://Google.com");
startActivity(intent1);
}
}
WebViewPage.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewPage extends Activity {
Intent intent;
WebView webView;
//key down
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
WebView webView =(WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
intent = getIntent();
String name = intent.getExtras().getString("name");
webView.loadUrl(name);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(getString(R.string.app_name));
mToolbar.setNavigationIcon(R.drawable.ic_home_black_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
You have two webView variables inside of class and inside of 'onCreate'
Remove webView variables in onCreate.
Example)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewPage extends Activity {
Intent intent;
WebView webView;
//key down
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
intent = getIntent();
String name = intent.getExtras().getString("name");
webView.loadUrl(name);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(getString(R.string.app_name));
mToolbar.setNavigationIcon(R.drawable.ic_home_black_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
Ya guys i have tried a lot of answers on this website and that all doesn't work at all
I have a webview app that i would love to save image in the website.
I have implemented long press to copy text in the app.
but not able to save image on long press.
those answers on context is not working
this is my main activity code can anyone please edit and answer me
and keep in mind that i only have some basic coding in java and I made most of this app from the codes of different sources
My Main Activity:
package com.example.ragulsundaram.typicaltamilan;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
SwipeRefreshLayout swipe;
private long backPressedTime;
private static final String TAG = "MainActivity";
public static int TIME_OUT=4000;
#Override
public void onBackPressed() {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
return;
}else{
Toast.makeText(getBaseContext(),"Press back again to exit,",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()){
mWebView.goBack();
}
else {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
}else{
Toast.makeText(getBaseContext(),"Press back again to exit",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"Pogatheeey",Toast.LENGTH_SHORT).show();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Vankakkam",Toast.LENGTH_LONG).show();
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
public void onRefresh(){
LoadWeb();
}
});
LoadWeb();
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_DENIED){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
}
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
}
});
}
public void LoadWeb()
{
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.loadUrl("https://typicaltamila.blogspot.com/ ");
swipe.setRefreshing(true);
mWebView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReveivedError(WebView view, int errorCode, String description, String failingUrl){
mWebView.loadUrl("file://android_asset/error.html");
}
public void onPageFinished(WebView view, String url)
{
//hide the swipe refreshlayout
swipe.setRefreshing(false);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith("magnet")) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in system.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
//torrent
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url=request.getUrl().toString();
if (url.startsWith("magnet")) { Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in Android.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
//downloading files
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request= new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = android.webkit.CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription(("Downloading"));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url,contentDisposition,mimetype));
DownloadManager dm=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(MainActivity.this,"Your file is downloading",Toast.LENGTH_SHORT).show();
}
});
}
}
In order to extend AppCompatActivity in a MainActivity.java file, the following was migrated from:
package me.site.site;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://third.second.tld/");
mWebView.setWebViewClient(new com.androidwebviewapp.karthik.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
return super.onCreateOptionsMenu(menu);
}
}
To
package me.site.site;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("https://third.second.tld/");
mWebView.setWebViewClient(new me.site.site.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item=menu.findItem(R.id.share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
** mShareActionProvider.setOnShareTargetSelectedListener(this); **
return(super.onCreateOptionsMenu(menu));
}
}
complains with an error referring to the code highlighted above
Error:(67, 33) error: method setOnShareTargetSelectedListener in class
ShareActionProvider cannot be applied to given types;
required: OnShareTargetSelectedListener
found: MainActivity
reason: actual argument MainActivity cannot be converted to OnShareTargetSelectedListener by method invocation conversion