I' am facing two issues in android webview.
Screen displaying blank when the screen orientation changes.
and
To store cookies(username and passwords) permanently, Presently it storing for only one day, when I open my app in next day, it is asking the login credentials once again.
Please help me . Thank you
public class MainActivity extends AppCompatActivity {
private WebView webView;
ProgressBar webpageprogressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView2);
webpageprogressbar = (ProgressBar) findViewById(R.id.progressBar);
webpageprogressbar.setProgress(0);
webpageprogressbar.setMax(100);
MainActivity.this.webpageprogressbar.setProgress(0);
if(savedInstanceState !=null)
{
webView.restoreState(savedInstanceState);
}else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccess(true);
}
CookieSyncManager.createInstance(MainActivity.this);
CookieManager manager = new CookieManager();
Log.i("My APP","At onCreate");
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
final Activity activity = this;
webView.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView web = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (web.canGoBack()) {
web.goBack();
return true;
}
break;
}
}
return false;
}
});
webView.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("My APP","At shouldOverrideRlLoading");
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d("My APP", "At onPageFinished");
CookieSyncManager.getInstance().sync();
super.onPageFinished(view, url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
if(newProgress ==100)
{
webpageprogressbar.setVisibility(View.GONE);
}else {
webpageprogressbar.setVisibility(View.VISIBLE);
}
}
});
if (savedInstanceState == null) {
Log.d("My APP","At savedInstanceState");
webView.loadUrl("http://google.com");
}
if (Build.VERSION.SDK_INT >= 19) {
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
}
public void setValue(int progress) {
MainActivity.this.webpageprogressbar.setProgress(progress);
}
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}
#Override
protected void onResume() {
Log.d("My APP","At onResume");
CookieSyncManager.getInstance().startSync();
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
Log.d("My APP","At onPause");
CookieSyncManager.getInstance().stopSync();
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Manifest file:-
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme" >
Add undermentioned tag to your manifest file in where the activity is declared:
android:configChanges="keyboardHidden|orientation|screenSize"
eg:<activity
android:name="com.test.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="landscape" />
To Store cookie:
// Create instance
CookieSyncManager syncManager = CookieSyncManager.createInstance(webView.getContext());
// Get instance
CookieManager cookieManager = CookieManager.getInstance();
// Set cookie
cookieManager.setCookie();
// Sync cookie
syncManager.sync();
feel free to ask for any query.
Related
Need some advice. I want to be able to redirect the user to a specific link in WebView. Example: we go to the first link and if it directs us to "google.com" then we will have to direct the user to "http://test.com". I made an implementation, put a redirect in shouldOverrideUrlLoading, however, after SplashScreen-loading image done its work, a white background appears and that's it. At the same time, if you remove the code for redirection, then after performing its work, the SplashScreen - loading image, the first link opens and the page from the Internet is displayed correctly. How do I redirect to other pages after opening the first one?
public class MainActivity extends AppCompatActivity {
private WebView webView;
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://test/start");
new TaskForRedirecting().execute();
}
public class TaskForRedirecting extends AsyncTask<Boolean, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Boolean... booleans) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Start loading here");
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return false;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return false;
} else {
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
view.loadUrl(request.getUrl().toString());
return false;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return false;
}
return true;
}
};
webView.setWebViewClient(webViewClient);
Log.d(TAG, "Do in background: APP is Working!!!");
}
});
return false;
}
#Override
protected void onPostExecute(Boolean success) {
success = false;
if (success) {
Toast toast = Toast.makeText(MainActivity.this, "App is under maintenance!", Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(MainActivity.this, "Let's start to work!", Toast.LENGTH_SHORT);
toast.show();
}
Log.d(TAG, "upload - final! ");
}
}
}
public class SplashScreenActivity extends AppCompatActivity {
long Delay = 6000;
private final String TAG = "SplashScreenActivity";
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
new SplashScreen().execute();
}
public class SplashScreen extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void...voids) {
Timer RunSplash = new Timer();
TimerTask ShowSplash = new TimerTask() {
#Override
public void run() {
finish();
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
}
};
RunSplash.schedule(ShowSplash, Delay);
Log.d(TAG, "ShowSplash - final! ");
return null;
}
}
}
Your implementation needs to change a bit, we don't need to set the webview client inside an AsyncTask, instead, we can set it directly but it should be set before we call loadurl.
I have removed the asynctask, and set the client in onCreate method before calling loadUrl.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return true;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
return true;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
};
webView.setWebViewClient(webViewClient);
webView.loadUrl("http://test/start");
}
UPDATE
Please check out the shouldOverrideUrlLoading Doc, You should return true when you want to cancel the current load, so when you want to load a different URL, then return true else return false to continue the current load. Returning false means the URL which is being loaded to the webview will continue, your custom URL will not be loaded.
my webview app opens a website that i need to login. but if i login and destroy the app, i need to login again. i want to cache login data and no need to login again until i log out. how can i make the webview app like holding caches? if user dont logout, app must to stay logged in. thanks for helping
here is my code:
WebView webid;
String newString;
ImageView loading;
AnimationDrawable animation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webid = (WebView) findViewById(R.id.webid);
loading = (ImageView)findViewById(R.id.loader);
animation = (AnimationDrawable) loading.getDrawable();
WebSettings webSettings = webid.getSettings();
webSettings.setJavaScriptEnabled(true);
webid.loadUrl("https://ios.mavicell.com");
webid.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
loading.setVisibility(View.VISIBLE);
animation.start();
}
#Override
public void onPageCommitVisible(WebView view, String url) {
super.onPageCommitVisible(view,url);
loading.setVisibility(View.INVISIBLE);
animation.stop();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loading.setVisibility(View.INVISIBLE);
animation.stop();
}
});
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("urlayar");
}
} else {
newString= (String) savedInstanceState.getSerializable("urlayar");
}
if (newString != null) {
webid.loadUrl(newString);
webid.getSettings().setJavaScriptEnabled(true);
webid.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
loading.setVisibility(View.VISIBLE);
animation.start();
}
#Override
public void onPageCommitVisible(WebView view, String url) {
super.onPageCommitVisible(view,url);
loading.setVisibility(View.INVISIBLE);
animation.stop();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loading.setVisibility(View.INVISIBLE);
animation.stop();
}
});
}
else {
}
// Logging set to help debug issues, remove before releasing your app.
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.init();
}
#Override
public boolean onKeyDown(int keyCode, #NonNull KeyEvent event){
if(event.getAction() == KeyEvent.ACTION_DOWN){
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Mavicell");
builder.setMessage("Çıkmak istediğinize emin misiniz?");
builder.setNegativeButton("Hayır", null);
builder.setPositiveButton("Evet", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.show();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
This below line should do your work
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT)
I have set orientation MainWebActivity to PORTRAIT and GameActivityLandscape to LANDSCAPE in AndroidManifest.xml when i start activity GameActivityLandscape in shouldOverrideUrlLoading ,but when i press back button from GameActivityLandscape then there appears a blank page,I want MainWebActivity as like first time load
My MainWebActivity is
public class MainWebActivity extends Activity {
private WebView myWebView;
ProgressBar progressBar;
boolean internet;
Bundle webState=null;
String GMTag="MainWebActivity ";
static String lodUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
myWebView = (WebView) findViewById(webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new myWebClient());
myWebView.setWebChromeClient(new WebChromeClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
//myWebView.clearCache(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
if (savedInstanceState == null) {
Log.d(GMTag, " onResume webview load ");
myWebView.loadUrl("http://html5games.com/Game/Civilizations-Wars-Master-Edition/2001681a-0f53-4691-9318-04e419ac7c0c");
}
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
Log.d(GMTag, "Main Web shouldOverrideUrlLoading test" + url.toString());
return handleUri(url);
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
Log.d(GMTag, "Main Web android N shouldOverrideUrlLoading " + request.getUrl().toString());
//final Uri uri = request.getUrl();
return handleUri(request.getUrl().toString());
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
/*public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
//Your code to do
Toast.makeText(MainWebActivity.this, "Your Internet Connection May not be active Or " + error.getDescription() , Toast.LENGTH_LONG).show();
}*/
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if(errorCode==404){
Toast.makeText(MainWebActivity.this, "File or directry not found" , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainWebActivity.this, "Your Internet Connection May not be active Or " + description, Toast.LENGTH_LONG).show();
}
}
}
private boolean handleUri(String url) {
if (url.contains("fg_domain=play.famobi.com&fg_aid=A1000-1&fg_uid=2001681a-0f53-4691-9318-04e419ac7c0c&fg_pid=4638e320-4444-4514-81c4-d80a8c662371&"))
{
Intent myIntent = new Intent(MainWebActivity.this, GameActivityLandscape.class);
myIntent.putExtra("URL", url); //Optional parameters
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
MainWebActivity.this.startActivity(myIntent);
progressBar.setVisibility(View.GONE);
} else {
myWebView.loadUrl(url);
}
return true;
}
#Override
protected void onPause() {
super.onPause();
myWebView.onPause();
Log.d(GMTag, " Web onPause called " + webState);
}
#SuppressLint("SetJavaScriptEnabled")
#JavascriptInterface
#Override
protected void onResume() {
super.onResume();
myWebView.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.d(GMTag, " onSaveInstanceState ");
super.onSaveInstanceState(outState);
webState=outState;
myWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(GMTag, " webview restored in onRestoreInstanceState ");
super.onRestoreInstanceState(savedInstanceState);
myWebView.restoreState(savedInstanceState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
This is my GameActivityLandscape activity
public class GameActivityLandscape extends Activity {
private WebView myWebView;
static String gameRotation, gameUrl;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
gameRotation = intent.getStringExtra("ORIENTATION");
gameUrl = intent.getStringExtra("URL");
//progressBar=(ProgressBar)findViewById(R.id.game_progressBar);
myWebView = (WebView) findViewById(R.id.game_webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new myWebClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
if (savedInstanceState == null) {
myWebView.loadUrl(gameUrl);
}
}
public class myWebClient extends WebViewClient {
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.d("Game", "onError landscape called " + failingUrl);
}
}
#Override
protected void onResume() {
super.onResume();
myWebView.onResume();
Log.d("Game", "onresume called of gameacticity landcape ");
}
#Override
protected void onPause() {
super.onPause();
Log.d("Game", "onPause called of gameacticity landcape ");
myWebView.onPause();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.i("Gaming mania", "Play game landscape activity finish");
finish();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
I have a webview as fragment which extends fragment class in my fragment navigation drawer. I want to detect the back press of this fragment.
Below is code i m using to detect the back press on the fragment
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
// handle back button
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container,new MyFragment()).commit();
return true;
}
return false;
}
});
In my webview this method is not getting called everytime i pressed back button
public class WebViewFragment extends Fragment {
static View view;
private WebView webView;
private String url;
static int count = 0;
LinearLayout llayout;
MyProgressDialog progressDialog;
public WebViewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
((AdvancedActivity) getActivity()).getSupportActionBar().hide();
view = inflater.inflate(R.layout.activity_play_lesson, container, false);
//Get webview
webView = (WebView) view.findViewById(R.id.web_view_play_lesson);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setWebContentsDebuggingEnabled(true);
}
llayout = (LinearLayout) view.findViewById(R.id.linearLayout);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
url = getResources().getString(R.string.myurl);
url = "http://myurl//88";
System.out.println("url for myplay is "+url);
startWebView(url);
} catch (InflateException e) {
}
return view;
}
#SuppressLint("JavascriptInterface")
private void startWebView(String url) {
//Create new webviejijnw Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
/*
IstarProgressDialog progressDialog;
*/
//If you do not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new IstarProgressDialog(getContext());
progressDialog.setMessage("Loading... Please Wait...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
//Show loader on url load
public void onLoadResource(WebView view, String url) {
}
public void onPageFinished(WebView view, String url) {
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new ErrorFragment()).commit();
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setGeolocationEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
});
webView.loadUrl(url);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the state of the WebView
webView.saveState(outState);
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
// handle back button
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new MyFragment()).commit();
return true;
}
return false;
}
});
wakeLock.acquire();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Webview ", "The onStop() event");
}
}
I am getting error as The Web Page at file:///#/android_asset/webpage.htm could not be loaded as: Is a directory. in the emulator.
but my code is webView.loadUrl("file:///android_asset/webpage.htm");
First the page renders perfectly but again after rendering refreshes the page and does not get loaded and will get the web page not available.
If we could carefully see the url that has been given out by the android emulator there are two extra characters before android_asset.
Below is the code.
public class Catalog extends Activity {
final Activity activity = this;
WebView webView;
ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);//used for rendering percentage of loading
setContentView(R.layout.catalog_layout);
try{
webView = (WebView) findViewById(R.id.browserwebview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgressBarVisibility(true);
activity.setProgress(progress * 100);
if(progress == 100){
activity.setTitle(R.string.app_name);
}
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(activity, "Oh no!"+ description, Toast.LENGTH_SHORT).show();
}
#Override
public void onLoadResource (WebView view, String url) {
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return true;
}
});
webView.loadUrl("file:/android_asset/web/webpage.html");
}
catch (Exception e) {
e.printStackTrace();
}
ImageButton btnBack = (ImageButton)this.findViewById(R.id.buttonBackCatalog);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(webView.canGoBack()){
webView.goBack();
}else{
Intent myIntent = new Intent(view.getContext(), FCFActivity.class);`
`startActivityForResult(myIntent, 0);
}
}
});
/*
* Actions for footer Buttons
*
*/
ImageButton buttonFooterMainHome = (ImageButton)findViewById(R.id.footerMainBtnHome);
buttonFooterMainHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), FCFActivity.class);
startActivityForResult(myIntent, 0);
}
});
LinearLayout homeLinearLayout=(LinearLayout)this.findViewById(R.id.footerLayoutHome);
homeLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), FCFActivity.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
}
}
}
Looking forward to your reply.
thanks.
Oh this caused me headaches, and they changed how it worked for one of the android versions, but can't remember which. Here is what I do:
webView.loadUrl("file:/android_asset/webpage.html");
and if your static webpage has images you use this link:
file:///android_asset/yourimage.png
Edit try this: https://stackoverflow.com/a/8737547/969325, clean project and check if asset file is at path.
- `You are using only htm use html`
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new myWebClient());
webview.loadurl();
and
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}