I'm making my own android app some people using my app says the app resets on rotate. But I cannot figure out whats wrong? I'm pretty new to app development thanks for the help!
App Mainactivity.java
package com.danielchr.hukeplan;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView wb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wb = (WebView) findViewById(R.id.webView);
WebSettings webSettings = wb.getSettings();
webSettings.setJavaScriptEnabled(true);
wb.loadUrl("https://www.hukeplan.com/");
wb.setWebViewClient(new WebViewClient());
if (savedInstanceState != null) {
wb.restoreState(savedInstanceState);
} else {
wb.loadUrl("https://hukeplan.com");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
wb.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
}
#Override
public void onBackPressed() {
if (wb.canGoBack()) {
wb.goBack();
} else {
super.onBackPressed();
}
}
}
I don't know how to fix the rotate problem.
if you want to show the WebView in only portrait mode than you may write this in your
android:screenOrientation="portrait"
or you may write below in your tag in your AndroidManifest
android:configChanges="keyboardHidden|orientation|screenSize"
This will prevent activity from loading again on orientation changes
or you may also override this method in your activity to handle orientation changes.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
Related
I've been trying to alter my Webview app to not show the header of the source url that it loads. I've gone trough all the methods provided in Stack Overflow's history and havent't got any of them working - so i'm doing something right, or those aren't working anymore?
My goal is to find a way to affect the CSS of the page loaded to the webview app (hide the header and footer for example). Most of the methods provided here earlier based on Javascript, which is not familiar with me. I'm open for any help, since it is my first project that i'm building, and my knowledge at this point is not too good.
Here's my MainActivity.java at the moment:
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.setWebViewClient(new WebViewClient());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
WebView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};", null);
} else {
WebView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};");
}
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
Okay finally found a way to hide the CSS elements. Added the whole code below and the key was to use the onPageFinished method. While it is not perfect, and only activates after the whole page is loaded, it's still a valid method to hide elements in my case.
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
/* HIDE UNWANTED CSS ELEMENTS */
WebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// hide element by class name
WebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('class-name-here')[0].style.display='none'; })()");
// hide element by id
WebView.loadUrl("javascript:(function() { " +
"document.getElementById('header').style.display='none';})()");
}
});
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
The features are enabled once the onCreate() methood is executed for the first time, but after i do a screen rotation none of the features get saved, even though I've overridden the onSaveInstanceState() method and I've also tried using the onRestoreInstanceState() method.
Kindly help me out.
I'll attach the code below.
Activity file
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main3Activity extends AppCompatActivity implements LoaderManager.LoaderCallbacks{
Toolbar toolbar;
WebView webView;
ProgressDialog progressDialog;
final String urld="https://www.google.co.in/";
final int LOADER_ID=1;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
webView = (WebView)findViewById(R.id.wb1);
progressDialog = new ProgressDialog(Main3Activity.this);
progressDialog.setTitle("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(true);
if(savedInstanceState!=null)
{
webView.restoreState(savedInstanceState);
webView.getSettings().setJavaScriptEnabled(true);
}
else {
webView.getSettings().setJavaScriptEnabled(true);
webView.setFocusable(true);
webView.setFocusableInTouchMode(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//webView.setInitialScale(1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setBackgroundColor(Color.WHITE);
//webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
//webView.setWebChromeClient(new WebChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if( URLUtil.isNetworkUrl(url) ) {
return false;
}
if (appInstalledOrNot(url)) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
} else {
// do something if app is not installed
}
return true;*/
if (Uri.parse(url).getHost().endsWith("google.co.in")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
super.onPageFinished(view, url);
}
});
}
bundle = savedInstanceState;
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(LOADER_ID, null, this);
}
/*private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}*/
#Override
public void onBackPressed() {
if(webView.canGoBack())
{
webView.goBack();
}
else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader onCreateLoader(int i, Bundle bundle) {
return new LoadingPageInBackground(this,urld,bundle,webView,progressDialog);
}
#Override
public void onLoadFinished(Loader loader, Object o) {
}
#Override
public void onLoaderReset(Loader loader) {
//webView.setVisibility(WebView.GONE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
Toast.makeText(Main3Activity.this,"Saved",Toast.LENGTH_SHORT).show();
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
webView.restoreState(state);
Toast.makeText(Main3Activity.this,"Restored",Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(state);
}
}
restoreState is not reliable, based on the documentation for restoreState :
If it is called after this WebView has had a chance to build state
(load pages, create a back/forward list, etc.) there may be
undesirable side-effects. Please note that this method no longer
restores the display data for this WebView.
Based on the documentation for saveState:
Please note that this method no longer stores the display data for
this WebView
You have to reload your WebView in onCreate(). You can store the URL in SharedPreference and load it in onCreate().
Another alternative is to handle the Orientation by your self and keep WebView unchanged. You can handle the orientation change by adding android:configChanges="orientation" in your manifest and Overriding onConfigurationChanged().
*Solved
I just had to publicly declare my webview variable for my back button class to work correctly. Thanks for the help
I've got a unique setup with the webview class and everything I've googled I've gotten nowhere.
I'm using buttons to launch webview's and I'm getting the issue that when I press the back button to return to my main app screen it will just kill the app. I have added some code in at the bottom to try and fix my issue but it has not worked.
btw the below code has been updated to what is currently working for me.
package my.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;
public class MobileAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
WebView wb;
public void onMyButtonClick01(View view)
{
Toast.makeText(this, "Pay your dues here!", Toast.LENGTH_SHORT).show();
wb = new WebView(this);
wb.loadUrl("http://www.link1.html");
setContentView(wb);
}
public void onMyButtonClick02(View view)
{
Toast.makeText(this, "Re-Sign here!", Toast.LENGTH_SHORT).show();
wb = new WebView(this);
wb.loadUrl("http://www.link2.html");
setContentView(wb);
}
public void onBackPressed () {
if(wb != null) {
if(wb.canGoBack()) {
wb.goBack();
} else {
setContentView(R.layout.main);
wb = null;
}
} else {
super.onBackPressed();
}
}
}
I assume you're saving off wb elsewhere? Not sure how you're accessing that from onBackPressed(). Let's say you do have a way to fetch it.
public void onBackPressed () {
if(wb != null) {
if(wb.canGoBack()) {
wb.goBack();
} else {
setContentView(R.layout.main);
wb = null;
}
} else {
super.onBackPressed();
}
}
I am very new to Java and Android programming. Just want a simple browser that enables users to visit my forum. I got this error in my java code:
>> Code: Webview webview; << Simple object code at the top of app. Causes: Syntax error on token "WebView", import expected.
Here's the full .java file code:
package com.droidisland.app;
WebView webview;
import android.app.Activity;
public class DroidIslandActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://droidisland.net");
}
}
You are declaring a WebView variable above your import statements and outside of the class. Move that declaration after the class declaration line, like this
public class DroidIslandActivity extends Activity {
WebView webview;
In your activity you can have this code:
/*
* entry point of the application starting the index.html of PhoneGap
* */
package com.capgemini.gm.myapp;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.util.Log;
import com.google.analytics.tracking.android.EasyTracker;
public class MyAppMainActivitiy extends DroidGap
{
String curPhoneNumber;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/app/index.html",15000);
}
#Override
public void onStart() {
super.onStart();
this.appView.addJavascriptInterface(new JsInterface(), "android");
Log.d("App start activity", "interface added");
curPhoneNumber = "test";
// The rest of your onStart() code.
EasyTracker.getInstance().activityStart(this); // Add this method.
}
#Override
public void onDestroy()
{
super.onDestroy();
com.google.analytics.tracking.android.EasyTracker.getInstance().activityStop(this);
}
public class JsInterface{
public String getPhoneNumber()
{
return curPhoneNumber;
}
}
}
and in your index.html you can have this script:
<script type="text/javascript">
alert(android.getPhoneNumber());
</script>
I'm making an android app and if I am at the very top of my WebView and I try to switch my phone into landscape mode, then it wont resize the webpage to fit my phones screen. It will only take up half of the screen, but then if I scroll down a little bit and switch to landscape mode it works fine!
I have android:configChanges="orientation" in the Android Manifest to keep the webview from resetting when i do change the orientation.
^^Note^^
Even if you are a tenth of a inch from the top of the page it will work fine, but if you are all the way at the top of the page it won't work.
This is the class im having problems with:
package my.app.name;
import my.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ConverterCatalogActivity extends Activity {
WebView browser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Set the Content View */
setContentView(R.layout.main);
/* Get the WebView */
WebView wv1 = (WebView) findViewById(R.id.wv1);
/* Activate JavaScript */
wv1.getSettings().setJavaScriptEnabled(true);
wv1.canGoBack();
browser=(WebView)findViewById(R.id.wv1);
browser.loadUrl("file:///android_asset/index.html");
/* Prevent WebView from Opening the Browser */
wv1.setWebViewClient(new InsideWebViewClient());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// We do nothing here. We're only handling this to keep orientation
// or keyboard hiding from causing the WebView activity to restart.
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if(browser.canGoBack()){
browser.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
/* Class that prevents opening the Browser */
private class InsideWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Here's a screenshot of it in landscape mode.
I've had issues with WebViews doing this before. Try measuring the view in OnOrientationChanged and it may fix your problem!
#Override
public void onSaveInstanceState(Bundle outState) {
((WebView) mView.findViewById(R.id.webView)).saveState(outState);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}