First i will paste my code.
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
mTabHost.setCurrentTab(0);
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
WebSettings webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
webview.restoreState(savedInstanceState);
webviewtwo.restoreState(savedInstanceState);
}
else{
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwoSettings.setDefaultFontSize(30);
webviewtwo.loadUrl("http://zsee.bytom.pl/plany/index.html");
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onSaveInstanceState(Bundle outState, Bundle Test) {
webview.saveState(outState);
webviewtwo.saveState(Test);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("Pomoc");
alertdialog.setMessage("Lepszy Planer od Sierran'a :>");
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
System.out.print("ss");
default:
return super.onOptionsItemSelected(item);
}
}
}
Now is my question. I have two webview widget. One is called webview and another webviewtwo. I'm newbie in android programing so i have problem how save two widgets in onSaveInstanceState and how restore them. Now webviewtwo overwrite webview and in webview windows i have page from webviewtwo. How fix it and do it right ?
Sierran
It's my understanding that onSaveInstanceState should be used to persist any dynamic state information needed to rebuild the application. You wouldn't want to persist the actual widget but rather the information that the widget needs to restore itself.
onSaveInstanceState takes only one Bundle.
Save the webview states into separate Bundles, then put them into the saved one:
Bundle state1=new Bundle();
webview.saveState(state1);
Bundle state2=new Bundle();
webviewtwo.saveState(state2);
outState.putBundle("state1",state1);
outState.putBundle("state2",state2);
super.onSaveInstanceState(outState);
Restoring:
webview.restoreState(savedInstanceState.getBundle("state1"));
webviewtwo.restoreState(savedInstanceState.getBundle("state2"));
Related
How can an options menu item be accessed from an object outside of the menu itself? I'm trying to set an alpha value for one of the options menu items, but it's not working for some reason. The commented lines are what I tried.
I've seen the following code used before, but it's not clear on where and how it should be used:
Drawable drawable = item.getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setAlpha(1);
}
Activity class
public class WebviewActivity extends AppCompatActivity {
private static final String TAG = WebviewActivity.class.getSimpleName();
WebView myWebView;
ProgressBar myProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_webview);
}
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.fragment_webview);
String url = getIntent().getStringExtra("url");
myWebView = findViewById(R.id.web_view);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
myProgressBar.setProgress(newProgress);
}
});
}
private class WebViewClient extends android.webkit.WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
String url=request.getUrl().toString();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
public void onBtnBackPressed() {
if (myWebView.canGoBack()){
myWebView.goBack();
} else {
onBackPressed();
}
}
public void onBtnForwardPressed() {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
// menu.getItem(R.id.action_webbrowser_forward).setEnabled(false);
// menu.getItem(R.id.action_webbrowser_forward).mutate();
// menu.getItem(R.id.action_webbrowser_forward).setAlpha(1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.web_browser, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() == R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() == R.id.action_webbrowser_forward) {
onBtnForwardPressed();
}
return super.onOptionsItemSelected(item);
}
}
Define in your activity class this variable:
MenuItem action_webbrowser_forward;
In onCreateOptionsMenu() after the inflation of the menu, write this:
action_webbrowser_forward = menu.findItem(R.id.action_webbrowser_forward);
then you can use it anywhere in your class:
action_webbrowser_forward.setEnabled(false);
but mutate is used for drawables and not menu items, so get the icon of the item by action_webbrowser_forward.getIcon() and apply mutate to it.
Try passing MenuItem reference on your onBtnForwardPressed function parameters :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() == R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() == R.id.action_webbrowser_forward) {
onBtnForwardPressed(item);
}
return super.onOptionsItemSelected(item);
}
And :
public void onBtnForwardPressed(MenuItem menuItem) {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
menuItem.setEnabled(false);
menuItem.getIcon().setAlpha(50);
}
}
Hope this helps
Okay I spend couple of hour to get this solution.apparently you can get menuitem from your toolbar. So in my case.
var menuItem = toolbar.menu;
Now to get specfic item from menu item
favIcon = menuItem.findItem(R.id.favourite);
Note: favIcon is MenuItem declare global
Now if you can do whatever you want to do for this icon
eg. to make it invisible
favIcon?.isVisible=false
Hi i've been searching a lot but couldn't find anything that could help.
I am creating an android app for our existing website. The website itself will load, but the main form where users can sign in won't load. Does anyone have any idea how this happens?
The website is https://app.one-2-ten.com/v2
p.s. This is the first time I am making an android app so sorry if its an obvious solution.
ProgressBar progressBar;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webView);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
}
else{
webView.getSettings() .setJavaScriptEnabled(true);
webView.getSettings() .setSupportZoom(false);
webView.getSettings() .setBuiltInZoomControls(false);
webView.getSettings() .setLoadWithOverviewMode(true);
webView.getSettings() .setUseWideViewPort(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new ourViewClient());
webView.Settings.AllowContentAccess = true;
webView.setWebChromeClient(new WebChromeClient(){
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);
}
}
}
);}
String data = getIntent() .getDataString();
if(Intent.ACTION_VIEW.equals(getIntent() .getAction())){
webView.loadUrl(data);
}else{
webView.loadUrl("https://one2ten-system.parseapp.com/v2");
}
}
public class ourViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
if (url.contains("one2ten-system.parseapp.com/v2")) {
v.loadUrl(url);
CookieManager.getInstance().setAcceptCookie(true);
} else {
Uri uri = Uri.parse(url);
startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
}
I've found what my issue was, I forgot to add the following line: webView.getSettings().setDomStorageEnabled(true);
This enables the browser to store user data from forms for example, which it needs because you land on a login page.
If my answer is incomplete please let me know!
Thanks
I have a WebView app and would like to add a splash screen to show either while loading the page, or for a set amount of time. I have tried some other solutions but could not find one that worked. If necessary to know, my splash image is splash.png, located in the drawable folder.
Here is my MainActivity.java
public class MainActivity extends Activity {
private GoogleApiClient client;
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView);
if(webView.canGoBack()){
webView.goBack();
}
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap Twice To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyBrowser());
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
if(isNetworkStatusAvialable (getApplicationContext())) {
view.loadUrl("file:///android_asset/index.html");
} else {
view.loadUrl("file:///android_asset/error.html");
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
#Override
public void onStart() {
super.onStart();
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"MLINKS",
Uri.parse("http://host/path"),
Uri.parse("android-app://PACKAGE-NAME/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"MLINKS",
Uri.parse("http://host/path"),
Uri.parse("android-app://PACKAGE-NAME/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
}
Thank you for any help!
EDIT:
Define a Progress Dialog:
private ProgressDialog pd;
Then inside your:
view.setWebViewClient(new MyBrowser() {
Insert this:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
I did something like this at one time. IIRC, it went like this:
First, I created a special ImageView subclass that overrode onTouchEvent() and threw away all the events.
Then for my layout, I had my ImageView subclass overlay the WebView then made it hidden, like this (for example):
<FrameLayout
...
>
<WebView
...
/>
<com.example.TouchHandlerImageView
....
android:src="R.drawable.splash"
android:visibility="gone"
/>
....
</FrameLayout>
Then my code went like this:
Show the splash imageview. (The onTouchEvent() would keep touch events from going through to the WebView underneath)
Start the page loading (In my case, I also had to run some javascript to set up the page)
In WebViewClient onPageFinshed(), hide the splash imageview, displaying the WebView with page fully loaded.
at first thing make a background and show it im main screen till the data is being ready.
use AsyncTask Class because it has 3 methods which them
1- onPreExecute() //don't do anything here
2- doInBackgroundProcess()// fetch your data here
3- onPostExecute()//get back the original background
I'm following (Building Web Apps in WebView) tutorial, but I have problem with (Navigating web page history) I'm runing it on my device and I click on a link but when I click the back button the application shuts down:
That's my activity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView myWebView = null;
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
public class MainActivity extends Activity {
WebView myWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"