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
Related
I have a NavigationView to place a drawer in an activity and want to use it across multiple activities
Activity:
public class MainActivity extends MenuOptions {
private DemoFragmentCollectionAdapter adapter;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.primaryToolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.cameraIcon:
menuItem.setChecked(true);
Toast.makeText(MainActivity.this, "Camera", Toast.LENGTH_LONG).show();
drawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
}
MenuOptions class:
public class MenuOptions extends AppCompatActivity {
private DrawerLayout drawerLayout;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.settingsIcon:
drawerLayout.openDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_LONG).show();
return true;
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(), "Home icon", Toast.LENGTH_LONG).show();
return true;
default:return super.onOptionsItemSelected(item);
}
}
}
But when I try to tab the home button (which is converted to a drawer menu icon) the app crashes and I get this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
How to solve this issue?
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 want to Prevent Page reload or Freeze the Current Web-view When I Select any menu from option menu
This is My Webview
public class MyWebV extends AppCompatActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mwview);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb1);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.web5);
WebSettings set = webView.getSettings();
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
set.setJavaScriptEnabled(true);
set.setJavaScriptCanOpenWindowsAutomatically(true);
set.setLoadWithOverviewMode(true);
set.setUseWideViewPort(true);
set.setDomStorageEnabled(true);
set.setAllowUniversalAccessFromFileURLs(true);
set.setJavaScriptCanOpenWindowsAutomatically(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final ProgressDialog progressBar = ProgressDialog.show(MyWebV.this, "Please Wait", "Loading...");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient()
{
public void onLoadResource (WebView view, String url) {
if (progressBar == null) {
progressBar.setTitle("Please Wait !");
progressBar.setMessage("Loading...");
progressBar.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.setWebChromeClient(new WebChromeClient() {
String url = "www.example.com/login.php";
webView.loadUrl(url);
}
#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 onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_MyWebV, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.about1) {
Intent aboutIntent = new Intent(this, About.class);
startActivity(aboutIntent);
return true;
}
else if (id == R.id.set1) {
Intent webIntent = new Intent(this, Settings.class);
startActivity(webIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
I My Web-view I have Some Menus So When I click on any menu like Setting or About... It is showing But After that When I go back to Home with Option or Back arrow from Action Bar or Option Menu Its Reloading
So I need to login and And check the previous page its difficult for every time.. Can any one suggest me how to freeze web-view or How to prevent reload with the same app menus...
Update
This is my about Us class
public class About extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutus);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb3);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_about, menu);
/*something*/
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
Intent mypIntent = new Intent(this, MyWebV.class);
About.this.finish();
startActivity(mypIntent);
return true;
}
else if (id == R.id.about1) {
Intent aboutIntent = new Intent(this, About.class);
About.this.finish();
startActivity(aboutIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
so for example if this is action bar back
so When I click on arrow Its reloading the webview.. On device Hardware back I have disabled... on hardware back its fine but... On action bar back its Reloading
I have just performed a test using two activities, a MainActivity containing a webView just like yours, and a menu button that opens a second activity (About.java), using the exact same intent that you used in onOptionsItemSelected().
After opening About activity from the menu, if I press my phone's hardware back button, it returns to MainActivity without reloading the contents of the WebView, so it works as you expect.
I think the problem you are experiencing is with the code you use to go back to the main activity. You may be using an Intent to open your main activity again from your secondary activities, causing a new instance of your main activity to be created, triggering onCreate(), and thus re-creating your WebView and reloading the page.
To test if that's the case, you can add some debugging statements inside onCreate() using Log.d() or System.out.println(), to check if it's being called when you try to return to your main activity (MyWebV). If you see your debug messages in the logs, it's because you are not returning to your Main Activity properly.
The way you should close your secondary activities to return to your main activity is calling:
finish()
That method will close current activity and restore the previous activity in the stack (your MyWebV activity in this case), without re-creating it, just calling onStart() and onResume(), which wouldn't re-create your WebView or reload the page.
About us or Setting page code where you used your custom back event or hardware back event.I think you are creating activity again inside your back event which is doesn't require you just need to call finish method your Settings or About us page finish there and Webview page remain same as it is.Thats why i am requesting you post your code of one of page at least i can understand what you did exactly.
public class About extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutus);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb3);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_about, menu);
/*something*/
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
finish();
return true;
}
else if (id == R.id.about1) {
Intent aboutIntent = new Intent(this, About.class);
About.this.finish();
startActivity(aboutIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
#Override public boolean onOptionsItemSelected(MenuItem item)
{ int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
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
I followed a tutorial to set a navigation drawer and it worked in my main activity. Now I tried to move it to almost every other activity creating a BaseActivity, but after making changes, navigation drawer icon is inactive, and does nothing when pressed.
MainActivity code:
public class MainActivity extends BaseActivity {
private WebView mWebView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//Hide the semy cirle at th bottom of the action bar when the user slides to the top
mWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
//mainWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.stopLoading(); // may not be needed
switch (Locale.getDefault().toString()) {
case "es_ES":
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.es_ES.HTML");
break;
default:
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.en_US.HTML");
break;
}
}
#Override
public void onPageFinished(WebView view, String url) {
//sendRegistrationIdToBackend();
//getCookies();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("CommentsPopUp")) {
Intent a = new Intent(MainActivity.this, CommentsPopUpActivity.class);
startActivity(a);
} else if (url.contains("postPopUp")) {
Intent b = new Intent(MainActivity.this, PostPopUpActivity.class);
startActivity(b);
} else if (url.contains("ProfilePicPopUp")) {
Intent c = new Intent(MainActivity.this, ProfilePicPopUpActivity.class);
startActivity(c);
} else if (url.contains("PostPicPopUp")) {
Intent c = new Intent(MainActivity.this, PostPicsPopUpActivity.class);
startActivity(c);
} else if (url.contains("reloadIndex")) {
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
} else if (Uri.parse(url).getHost().length() == 0) {
return false;
} else { // Otherwise, give the default behavior (open in browser)
mWebView.loadUrl(url);
}
return true;
}
});
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
// Stop local links and redirects from opening in browser instead of WebView
// mWebView.setWebViewClient(new MyAppWebViewClient());
}
#Override
public void onBackPressed(){
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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void getCookies() {
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie("http://192.168.0.6/");
//Log.i("UdazzT", cookies);
}
}
BaseActivity code:
public class BaseActivity extends AppCompatActivity {
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
mNavItems.add(new NavItem(getResources().getString(R.string.myPosts), "", R.mipmap.ic_action_home));
mNavItems.add(new NavItem(getResources().getString(R.string.myFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.findFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profileInfo), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profilePic), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.notifications), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.contact), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.logOut), "", R.mipmap.ic_action_about));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
}
#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_base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle
// If it returns true, then it has handled
// the nav drawer indicator touch event
if (mDrawerToggle.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);
}
#Override
public void onBackPressed(){
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){ //replace this with actual function which returns if the drawer is open
mDrawerLayout.closeDrawer(Gravity.LEFT); // replace this with actual function which closes drawer
}
else{
super.onBackPressed();
}
}
/*
* Called when a particular item from the navigation drawer
* is selected.
* */
private void selectItemFromDrawer(int position) {
switch (position) {
case 0:
Intent a = new Intent(this, MyPostsActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(this, MyFriendsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(this, FindFriendsActivity.class);
startActivity(c);
break;
case 3:
Intent d = new Intent(this, MyProfileInfoActivity.class);
startActivity(d);
break;
case 5:
Intent f = new Intent(this, MyNotificationsActivity.class);
startActivity(f);
break;
case 6:
Intent g = new Intent(this, ContactActivity.class);
startActivity(g);
break;
case 7:
//mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/signOut.php");
break;
}
mDrawerList.setItemChecked(position, true);
//setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, String subtitle, int icon) {
mTitle = title;
mSubtitle = subtitle;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText(mNavItems.get(position).mTitle);
subtitleView.setText(mNavItems.get(position).mSubtitle);
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
i have given this answer.
refer to this https://stackoverflow.com/a/30490289/3498931 and
in your case, implement syncState() method after the setting the listener to mDrawerLayout.
mDrawerLayout.setDrawerListener(drawerToggle);
after this statement, use the code i given in link. also you have duplication of code, remove the code from class which is not applicable. both way it is possible, but keep one only whichever works to avoid further conflict, unreadability or confustion.