so i made a website which could be turned into mobile app simply by using webview. when the first time i install the apk, it work perfectly well but the problem is after that, the web is just static or it's not loaded anymore.
it just open up the same content like the first time i install it even though i already change the whole website. i don't know if the problem was with the webview or with the android.
i already try made a auto refresh/autoreload function in php but it only work in mobile browser and didn't work in my app...
anyone know any solution?
since i'm a newbie in android developping i'll put the whole code of my main activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//WebView
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mwebView.getSettings().setAppCacheEnabled(true);
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
mwebView.loadUrl("http://192.168.94.2/autorefresh/");
//force links open in webview only
mwebView.setWebViewClient(new MyWebviewClient());
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
mwebView.loadUrl("http://192.168.94.2/ee1/");
}
if (id == R.id.nav_kolam) {
mwebView.loadUrl("http://192.168.94.2/ee1/listkolam.php");
}
if (id == R.id.nav_pantai) {
mwebView.loadUrl("http://192.168.94.2/ee1/listpantai.php");
}
if (id == R.id.nav_transaksi) {
System.exit(0);
}
if (id == R.id.nav_about) {
System.exit(0);
}
if (id == R.id.nav_keluar) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//bikin progress dialog
private class MyWebviewClient extends WebViewClient {
//ProgressDialogue
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("192.168.94.2")) {
//open url contents in webview
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd=new ProgressDialog(MainActivity.this);
pd.setTitle("Mohon Tunggu Sebentar");
pd.setMessage("Website Loading..");
pd.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
super.onPageFinished(view, url);
}
}
//bikin tombol back halaman
#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 {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}}
i'm using native php
The webView caches all the Contents of the Site , so that it doesn't need to download images etc.
For you to get the updations you need to maintain versioning your files and have a cache-control = max-age on yout index.html file
mwebView.loadUrl("about:blank");
mwebView.loadUrl("http://192.168.94.2/ee1/");
Load blank page before loading any new url.
So add mwebView.loadUrl("about:blank"); before all your if-else cases.
May this help!
webView.loadUrl("javascript:window.location.reload(true)");
This may help to reload the webview. Thanks
Related
I'm using local html files which contains links in it but when i click on links it is not showing up progress bar & loading text in webview
this is my Mainactivity.java file
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
wv = (WebView)findViewById(R.id.webview);
wv.loadUrl("file:///android_asset/www/index.html");
wv.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_exit) {
System.exit(0);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebViewClient extends WebViewClient {
TextView txt = (TextView) findViewById(R.id.txtload);
ProgressBar pbar = (ProgressBar) findViewById(R.id.pg1);
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
wv.loadUrl("file:///android_asset/www/error.html");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
System.out.println("loading... please wait");
pbar.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("finished loading");
pbar.setVisibility(View.GONE);
txt.setVisibility(View.GONE);
}
}
}
content.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:id="#+id/txtload"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Loading... Please Wait"
android:textColor="#android:color/holo_orange_dark"
android:textSize="14sp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="209dp" />
<ProgressBar
android:id="#+id/pg1"
style="#android:style/Animation.Dialog"
android:layout_width="match_parent"
android:layout_height="44dp"
android:gravity="center"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="4dp" />
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light"></WebView>
</android.support.constraint.ConstraintLayout>
Android studio displays the views in the order that they appear in the XML file. What you need to do is reorder the views. The webview should be first then followed by the Textview and then the progress view.
Thing is, it's in the app and it's showing, just not to the user or to you while running the app. The webview is obscuring the others. See if it will help and mark as correct answer.
thanks for read my question :) I am not able to solve this problem after check all the forum. I am working on my first webview. Nothing special. It's a webview with progress bar. My code in "shouldOverrideUrlLoading" method is not working. I want that all external links of my site open in browser and not in app, but it does not work. Can anyone please check my code?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private WebView wv;
private ProgressBar progressBar;
private FrameLayout frameLayout;
SwipeRefreshLayout swipe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
String webUrl = wv.getUrl();
wv.loadUrl(webUrl);
}
});
LoadWeb();
}
public void LoadWeb(){
wv = (WebView)findViewById(R.id.webView);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.loadUrl("example.com");
swipe.setRefreshing(true);
wv.setWebViewClient(new HelpClient());
wv.setWebViewClient(new MyAppWebViewClient());
wv.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress){
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(progress);
if (progress == 100){
frameLayout.setVisibility(View.GONE);
}
super.onProgressChanged(view, progress);
}
});
progressBar.setProgress(0);
wv.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
swipe.setRefreshing(false);
}
});
}
private class HelpClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
frameLayout.setVisibility(View.VISIBLE);
return true;
}
}
private class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
#Override
public void onBackPressed() {
if(wv.canGoBack()) {
wv.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
wv.loadUrl("example.com");
} else if (id == R.id.nav_facebook) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/idfbpage"));
startActivity(intent);
} catch (Exception e) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/idfbpage"));
startActivity(intent);
}
} else if (id == R.id.nav_instagram) {
Uri uri = Uri.parse("http://instagram.com/_u/idinstapage");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://instagram.com/idinstapage")));
}
} else if (id == R.id.nav_star) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=idpackage"));
startActivity(intent);
} else if (id == R.id.nav_informazioni) {
wv.loadUrl("example.com/info-app");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
In your method LoadWeb() there is an error because your WebView should have only one WebViewClient and only one WebChromeClient. So what happens is, if you use the method wv.setWebViewClient(new YourWebViewClient()); more than once what happens is that all other methods set before that are ignored because you can set it only once.For your case:
You set the WebViewClient Three (3) times:
wv.setWebViewClient(new HelpClient()); //First time
wv.setWebViewClient(new MyAppWebViewClient()); //Second time
And the last time you set it down in your same method you set another like:
wv.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
swipe.setRefreshing(false);
}
});
So what happens is that the two previous methods were ignored and the only method that was working was the last one (the third) only. That's why I asked you to put the second method down to setWebClient((new MyAppWebViewClient()); so as to ignore the previous!
THE SOLUTION
Now you know we have to set only one WebViewClient for your webView we have to make only ONE Class that will be used to and do the job of all three other WebViewClient by overriding all the required methods. Make this class inside your activity but oustide your any method (just like how you have done when making in HelpClient() Class). Here is Our Class Please make sure you read the Comments in it!
private class NewWebViewClient extends WebViewClient {
//Now we have only one class to do a job of all the other three!
#Override
public void onPageFinished(WebView view, String url) {
/*I here do whatever you want to do when the page has finished loading! Do it here inside this method and it will work may be control the framelayout visibility For example lets setRefreshing false to our swipe()*/
swipe.setRefreshing(false);
//.....add more methods you want here when the page loading is finished
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*In this method we are going to tell the android system what kind of link we want and what kind of link we dont want for that what we want we will handle for the extra the browser should do so!*/
if (Uri.parse(url).getHost().endsWith("example.com")) {
//if the code gets here this is your link then right? Lets do whatever we want with our link and logic for example lets set framelayout visible or doing anything this link's host is example.com!
frameLayout.setVisibility(View.VISIBLE);
return false;
} else {
//Ooops This link is not yours lets just open browsers right
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
}
After your class is beautiful then lets just set our WebViewClient only ONCE.
wv.setWebViewClient(new NewWebViewClient());
You can just ignore the WebChromeClient because you set it only once you are good. Comment below if you find any difficulties!
I hope removing the this line
wv.setWebViewClient(new MyAppWebViewClient());
will solve the problem for you.
You are using two instances of WebViewClient ,remove one ,
private class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("TAG",url);
if(Uri.parse(url).getHost().equals("example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);//add the brakpoint here
Log.d("TAG","Starting activity");
return true;
}
}
just use this
I am developing an application where I am using a webview. Everything is working fine but when I try to open external links inside webview it either freezes or crashes.This happens on android 4.4 and below but works well on android 5.0 and above.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
///initialize webview
private WebView mwebview;
ProgressBar bar;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mwebview = (WebView) findViewById(R.id.myWebview);
bar = (ProgressBar) findViewById(R.id.progressBar2);
WebSettings webSettings = mwebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mwebview.loadUrl("http://stalls.co.ke/shopping");
// improve webview perfomance
mwebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
if (Build.VERSION.SDK_INT >= 19) {
mwebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mwebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mwebview.getSettings().setAppCacheEnabled(true);
mwebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
//force links to open in webview only
mwebview.setWebViewClient(new MyWebViewClient());
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
mwebview.loadUrl("http://stalls.co.ke/shopping");
} else if (id == R.id.nav_gifts) {
mwebview.loadUrl("http://stalls.co.ke/gifts-coupons");
} else if (id == R.id.nav_men) {
mwebview.loadUrl("http://stalls.co.ke/stallswear-men");
} else if (id == R.id.nav_women) {
mwebview.loadUrl("http://stalls.co.ke/stallswear-women");
} else if (id == R.id.nav_kids) {
mwebview.loadUrl("http://stalls.co.ke/stallswear-kids-baby");
} else if (id == R.id.nav_men_cosmetics) {
mwebview.loadUrl("http://stalls.co.ke/copy-of-stalls-cosmetics");
} else if (id == R.id.nav_women_cosmetics) {
mwebview.loadUrl("http://stalls.co.ke/copy-of-men-footwear");
} else if (id == R.id.nav_kids_cosmetics) {
mwebview.loadUrl("http://stalls.co.ke/copy-of-stalls-cosmetics");
} else if (id == R.id.nav_homes) {
mwebview.loadUrl("http://stalls.co.ke/home-kitchen-products");
} else if (id == R.id.nav_garden) {
mwebview.loadUrl("http://stalls.co.ke/garden-products");
} else if (id == R.id.nav_smarthomes) {
mwebview.loadUrl("http://stalls.co.ke/smart-home-products");
} else if (id == R.id.nav_eatery) {
mwebview.loadUrl("http://stalls.co.ke/stallseatery");
} else if (id == R.id.nav_customer_service) {
mwebview.loadUrl("http://stalls.co.ke/help");
} else if (id == R.id.nav_about_us) {
mwebview.loadUrl("http://stalls.co.ke/about-us");
} else if (id == R.id.nav_kijo) {
mwebview.loadUrl("http://stalls.co.ke/house-of-kinjo");
} else if (id == R.id.nav_Airi) {
mwebview.loadUrl("http://stalls.co.ke/Airi");
} else if (id == R.id.nav_mamapeter) {
mwebview.loadUrl("http://stalls.co.ke/house-of-kinjo");
} else if (id == R.id.nav_swahili) {
mwebview.loadUrl("http://stalls.co.ke/swahili-princess");
} else if (id == R.id.nav_allstalls) {
mwebview.loadUrl("http://stalls.co.ke/kenyan-stores");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
// go to previous page when back button is pressed
#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 {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
bar.setVisibility(view.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mwebview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(request.getUrl().toString());
}
return false;
}
});
} else {
mwebview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
return false;
}
}
}
This is my MainActivity.java file, I would like to know why this is happening.
try using WebChromeClient; instead of WebViewClient; see if it works.
I'm trying to make a webview application but I'm not good about it.
Just I wanna do that: I have a website and I wanna open external links in default browser like a target _blank.
My Activity:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
NavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
initInstances();
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.loadUrl("http://mywebsite.domain.com/myprofile/");
myWebView.setWebViewClient(new WebViewClient());
}
private void initInstances() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.hello_world, R.string.hello_world);
drawerLayout.setDrawerListener(drawerToggle);
navigation = (NavigationView) findViewById(R.id.navigation_view);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
String menu1 = "https://mywebsite.domain.com/myprofile/";
String menu2 = "https://mywebsite.domain.com/exit";
String menu3 = "https://mywebsite.domain.com/discover/";
String menu4 = "https://mywebsite.domain.com/settings/";
String menu5 = "https://mywebsite.domain.com/language";
String menu6 = "https://mywebsite.domain.com/vipmembership";
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient());
switch (id) {
case R.id.navigation_item_1:
myWebView.loadUrl(this.menu1);
break;
case R.id.navigation_item_2:
myWebView.loadUrl(this.menu2);
break;
case R.id.navigation_item_3:
myWebView.loadUrl(this.menu3);
break;
case R.id.navigation_item_4:
myWebView.loadUrl(this.menu4);
break;
case R.id.navigation_item_5:
myWebView.loadUrl(this.menu5);
break;
case R.id.navigation_item_6:
myWebView.loadUrl(this.menu6);
break;
}
return false;
}
});
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item))
return true;
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
I tired so many code about it but it's didn't work. Thanks a lot.
You have to send an Intent to to the default web browser, in order to open the link in the browser, so maybe something like this:
Create a class that extends WebViewClient, in this way:
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("https://mywebsite.domain.com")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
In your MainActivity, in the onCreate method, set the MyCustomWebViewClient before the call to loadUrl method, like this:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
NavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
initInstances();
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new MyCustomWebViewClient());
myWebView.loadUrl("http://mywebsite.domain.com/myprofile/");
}
// the rest of your code
I have almost 30 webview in a Tablayout. Everything works fine but my app consumes a lot of memory and will just close because of memory issue. This is what I get in log
04-05 21:00:09.458 19720-19801/com.example.choman.webview A/chromium: [FATAL:memory.cc(19)] Out of memory. size=16777216
This is my java file. Basically all the remaining 29 fragments contain the same code with just a change in the url. I am not sure how to handle this.
public class stackOverflow extends Fragment {
private WebView webView;
private ProgressBar progressBar1;
private SwipeRefreshLayout mSwipeRefreshLayout1;
public stackOverflow() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
progressBar1 = (ProgressBar) view.findViewById(R.id.progressBar1);
webView = (WebView) view.findViewById(R.id.website_detail_1);
webView.setWebViewClient(new MyAppWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://www.stackoverflow.com");
WebSettings webSettings = webView.getSettings();
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
mSwipeRefreshLayout1 = (SwipeRefreshLayout) view.findViewById(R.id.swipe1);
mSwipeRefreshLayout1.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl("http://www.stackoverflow.com");
}
});
if (mSwipeRefreshLayout1.isRefreshing()) {
mSwipeRefreshLayout1.setRefreshing(false);
}
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
}
public class MyAppWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.findViewById(R.id.progressBar1).setVisibility(View.GONE);
Log.i("pageFinished", "yesss");
//progressBar.setVisibility(View.INVISIBLE);
progressBar1.setVisibility(View.GONE);
if (mSwipeRefreshLayout1.isRefreshing()) {
mSwipeRefreshLayout1.setRefreshing(false);
}
}
#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;
}
}
}
Mainactivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("WebView1").setTag("WebView1"));
//all the way down to .....
tabLayout.addTab(tabLayout.newTab().setText("WebView30").setTag("WebView30"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(6);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout
.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(
tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.WebView1) {
viewPager.setCurrentItem(0);
//all the way down to..30
if (id == R.id.WebView30) {
viewPager.setCurrentItem(30);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the code for TabPagerAdapter
public class TabPagerAdapter extends FragmentStatePagerAdapter
{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs)
{
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
//
WebViewFragment1 tab1 = new WebViewFragment1();
return tab1;
//all the way to tab 29
webViewFragment30 tab30 = new WebViewFragment30();
return tab30
default:
return null;
}
}
#Override
public int getCount()
{
return tabCount;
}
}
Use ViewPager. ViewPager will hold maximum 3 fragments in memory at any time(without changing the default offscreen page limit). The 3 fragments are the current visible fragment, left and right side fragments to the current fragment.
If you want tabs, you could create a custom View which looks like the system Tabs and add it above the ViewPager. Use PageTransformer with ViewPager to track the ViewPager swipe and scroll the custom Tab accordingly. Then listen to the clicks of Tabs and scroll the ViewPager based on the Tab pressed.
Update:
I totally forgot that we could attach a TabLayout with a ViewPager instead of creating custom Tabs.
tabLayout.setUpWithViewPager(viewpager) will work.
Thanks to #choman
viewPager.setOffscreenPageLimit(6); This line is causing the issue. This line tells the view pager to keep (6+6+1 = 13) pages in memory which should be costly in your case since each page has 6.5 Mb of contents. You need to change it to viewPager.setOffscreenPageLimit(1) to fix the OutOfMemory issue.
Quoting your comment, "I am using only single webview in app but my webpage having 6.5MB size. So it was main reason of app crash".
If your webpage is 6.5MB size, my hunch is that it is because of some large size high quality images. If that is the case, you should consider reducing the size of the images by downscaling/ downsampling the images. Downscaling the images at the server side is much better than doing that in mobile after downloading(waste of bandwidth, CPU, battery).
You can use android:largeHeap="true" to request a larger heap size, but this will not work on any pre Honeycomb devices. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above.
it causes because your application need more space to run.
i think it will help you to solve out current problem.
--how to use--
<application
....
android:largeHeap="true" >
thanks
WebView is heavy component.
I would recommend to change your application to work with single webview and changing url in it instead of multiple webview usage.