This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I Build my own file sharing and website app using android studio.
The app is a very simple file sharing and website app, for which I already had to make a lot of fixes. Everything was working fine but in some phone it crashed.
Oh boy wasn't I wrong
The app builds fine, and working perfectly in my phone, but in some phones it will crashed.
below is my Videostatis.java which is connected to my website using wenview
--CODE--
package com.IApps.IndianShareIt.fragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import okhttp3.Request;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.IApps.IndianShareIt.ui.callback.IconSupport;
import com.IApps.IndianShareIt.ui.callback.TitleSupport;
import com.genonbeta.TrebleShot.R;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import static android.content.Context.DOWNLOAD_SERVICE;
import static androidx.core.content.ContextCompat.getSystemService;
/**
* A simple {#link Fragment} subclass.
*/
public class VideoStatus extends Fragment implements IconSupport, TitleSupport {
public WebView mWebView;
private Dialog loadingDialog;
private Handler handler = new Handler(){
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:{
webViewGoBack();
}break;
}
}
};
public VideoStatus() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_video_status, container, false);
mWebView = (WebView)v.findViewById(R.id.webviewVideo);
loadingDialog = new Dialog(getActivity());
loadingDialog.setContentView(R.layout.loading);
loadingDialog.getWindow().setBackgroundDrawable(getActivity().getDrawable(R.drawable.round_btn));
loadingDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
loadingDialog.setCancelable(false);
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(false);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.getSettings().setBuiltInZoomControls(false);
// mWebView.loadUrl("https://indianshareitwhatsappstatus.blogspot.com/2020/07/blog-post.html");
mWebView.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& mWebView.canGoBack()) {
handler.sendEmptyMessage(1);
return true;
}
return false;
}
});
mWebView.setWebViewClient(new WebViewClient());
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
if(haveNetworkConnection()){
mWebView.loadUrl("https://indianshareitwhatsappstatus.blogspot.com/2020/07/blog-post.html");
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loadingDialog.dismiss();
mWebView.setVisibility(View.VISIBLE);
}
});
} else {
mWebView.loadUrl("file:///android_asset/error.html");
final Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
if (haveNetworkConnection()) {
mWebView.loadUrl("https://indianshareitwhatsappstatus.blogspot.com/2020/07/blog-post.html");
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loadingDialog.dismiss();
mWebView.setVisibility(View.VISIBLE);
}
});
return;
}
mWebView.loadUrl("file:///android_asset/error.html");
ha.postDelayed(this, 1000);
}
}, 1000);
}
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 = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Downloading File Check Your Gallery When Download is Complete",
Toast.LENGTH_LONG).show();
}});
return v;
}
#Override
public int getIconRes() {
return R.drawable.ic_slow_motion_video_black_24dp;
}
#Override
public CharSequence getTitle(Context context) {
return context.getString(R.string.video_status);
}
private void webViewGoBack(){
mWebView.goBack();
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
My app has been stopped in some phones and shows this error
Watch your API-Level in your Manifest, in some cases, people have an older one than your minimum is
Related
I just make a web browser and uploaded on play store but This is not working on my some of friends device (redmi note 8),(redmi 9). when he click on link a blank page will come same as when divice is not connected to internet. my app link - https://play.google.com/store/apps/details?id=com.zimax.forxbrowser .
my java code of first page-
package com.zimax.forxbrowser;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.DownloadListener;
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.widget.TextView;
public class BrowserView extends AppCompatActivity {
private String url;
private ProgressBar progressBar;
SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser_view2);
final WebView webview = findViewById(R.id.webView);
final EditText urlET = findViewById(R.id.urlET);
final ImageView homeBtn = findViewById(R.id.homeIcon);
url = getIntent().getStringExtra("url");
final String urlData = url.substring(0, 4);
if(!urlData.contains("www")){
url = "www.google.com/search?q="+url;
}
urlET.setText(url);
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
urlET.setText(url);
}
});
//Progress Bar
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if(progress<100 && progressBar.getVisibility() == progressBar.GONE){
progressBar.setVisibility(ProgressBar.VISIBLE);
}
if(progress == 100){
progressBar.setVisibility(ProgressBar.GONE);
}
}
});
//BackButton
webview.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
urlET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH){
final String urlTxt = urlET.getText().toString();
if(!urlTxt.isEmpty()){
final String urlData = urlTxt.substring(0, 4);
if(!urlData.contains("www")){
url = "www.google.com/search?q="+url;
}
else {
url = urlTxt;
}
}
}
return false;
}
});
//download any thing
webview.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(url);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
I am expecting to work on all android similar to working on my device.
Im not and Android or Java Developer, I fullstack web developer..but I have a template for making webviews project that works in most of the cases...but with this login doesnt work..
I have a site tha use the facebook Js SDK Version 3.2
It works perfect on: Google Chrome in my Laptop.
It works perfect on: Google Chrome in my Phone
but in APP in the webView after i Insert user and password of Facebook and press login it freezes.
I think it cant return to the previous page..
I read a lot of post here but nothing works..
this is my MainActivity:
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String target_url = "https://myapp.com/gen_age/index.php";
private static final String target_url_prefix = "myapp.com/gen_age/index.php";
private WebView mWebview;
private WebView mWebviewPop;
private FrameLayout mContainer;
private SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebview = findViewById(R.id.webView);
mContainer = findViewById(R.id.webview_frame);
swipeLayout = findViewById(R.id.swipe_container);
final WebSettings webSettings = mWebview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mWebview.setWebViewClient(new UriWebViewClient());
mWebview.setWebChromeClient(new UriChromeClient());
mWebview.loadUrl(target_url);
swipeLayout.setRefreshing(true);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
//Do your task
mWebview.reload();
}
});
}
private class UriWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
swipeLayout.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
swipeLayout.setRefreshing(false);
}
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
swipeLayout.setRefreshing(false);
}
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
try {
String host = Uri.parse(url).getHost();
//Log.d("shouldOverrideUrlLoading", url);
if (host.equals(target_url_prefix)) {
// This is my web site, so do not override; let my WebView load
// the page
if (mWebviewPop != null) {
mWebviewPop.setVisibility(View.GONE);
mContainer.removeView(mWebviewPop);
mWebviewPop = null;
}
return false;
}
if (host.equals("m.facebook.com")) {
return false;
}
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
// swipeLayout.setRefreshing(false);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
swipeLayout.setRefreshing(false);
Log.d("onReceivedSslError", "onReceivedSslError");
//super.onReceivedSslError(view, handler, error);
}
}
#Override
public void onBackPressed() {
if (mWebview.canGoBack()) {
mWebview.goBack();
} else {
finish();
}
}
class UriChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(getApplicationContext());
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new UriWebViewClient());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
I'm gonna go out on a limb here and say you are doing IO operations (like trying to login by sending credentials over the internet) on the main UI thread. If this is the case, this is what is causing your app to freeze.
I couldn't find the actual code that is responsible for the login, but, if you are sending an HTTP request or something similar to it, you need to do it in a background thread, so that UI doesn't freeze.
The main thread in Android is responsible for updating the UI, and if you block it with a blocking IO operation, it will freeze.
I buit an webview app with Android Studio and in my website i have a link like tel:0752118 when i press this link from app return eror net::err_unknown_url_scheme
This is my MainActivity.java
package totalonlinesrl.totalonline;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.net.Uri;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
private LinearLayout layoutProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
webView.setVisibility(View.GONE);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDisplayZoomControls(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
webView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(false);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
super.onPageStarted(view, url, favicon);
}
});
if(isOnline()) {
webView.loadUrl("https://total-online.eu/");
} else {
String summary = "<html><body><font color='red'>No Internet Connection</font></body></html>";
webView.loadData(summary, "text/html", null);
toast("No Internet Connection.");
}
}
private void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
}
Any solution ?
If the links contain geographic locations, phone numbers, and email addresses, you can switch to the search screen and mail client using the code below.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
view.reload();
return true;
} else if (url.contains("mailto:")) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else if(url.contains("geo:")) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
return true;
} else {
view.loadUrl(url);
return true;
}
}
Can anyone please help me check my code to see why it cannot be
launched in the app itself but directs me to a browser? ): Thanks!!
MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;
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://intelligami.com/submitqn");
mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.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);
}});
}
private class MyWebViewClient extends MyAppWebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Where is the error? :D
It keeps opening up in the browser.
In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Hello coders out there!
I'm a beginner in android programming and my app won't show that there's no connection avaiable:
Shows: 404 HTML-screen |
Should-show: Message "no network connection"
Thank's for your help!
package net.schwarzis.htl_cloud;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
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.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("JavascriptInterface") public class MainActivity extends Activity {
/** Called when the activity is first created. */
private WebView browser = null;
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("Please connect to the internet...")
.setTitle("No network connection!");
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
builder.show();
return true;
}
return false;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
browser.loadUrl(url);
return true;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// connect to our browser so we can manipulate it
browser = (WebView) findViewById(R.id.mybrowser);
// get settings so we can config our WebView instance
WebSettings settings = browser.getSettings();
// JavaScript? Of course!
settings.setJavaScriptEnabled(true);
// clear cache
browser.clearCache(true);
final ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Lade...");
browser.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
pd.show();
browser.loadUrl(url);
return true;
}
});
// this is necessary for "alert()" to work
browser.setWebChromeClient(new WebChromeClient());
// add our custom functionality to the javascript environment
browser.addJavascriptInterface(new MyCoolJSHandler(), "Cloud");
// load a page to get things started
pd.show();
browser.loadUrl("http://cloud.schwarzis.net");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Lade...");
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(browser.canGoBack() == true){
pd.show();
browser.goBack();
}else{
pd.show();
finish();
}
pd.dismiss();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
final class MyCoolJSHandler
{
// write to LogCat (Info)
public void Info(String str) {
Log.i("GoingNative",str);
}
// write to LogCat (Error)
public void Error(String str) {
Log.e("GoingNative",str);
}
// Kill the app
public void EndApp() {
finish();
}
}
}
Make sure you have added the "Internet" permission in the Manifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Other than that, your code looks fine to me.
Hope it helps.