Android Webview displays different layout
My webview shows different layout. Different from when I look at it on a
browser. It was alright before but i don't know what I did but a certain
text is now floating higher.
Here's my code:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
//import android.net.Uri;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="sample.url.com";
private static String
helpurl="file:///android_asset/otherpages/helppage.htm";
private static String
fbackurl="file:///android_asset/otherpages/feedback.htm";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT,
mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
@SuppressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
if(reachable(this))
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
else
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
}
setContentView(R.layout.activity_main);
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 );
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder ad = new AlertDialog.Builder(
MainActivity.this );
ad.setTitle("Unreachable Host");
ad.setMessage("Host is unreachable. Load from cache or exit.");
ad.setIcon(R.drawable.tick);
ad.setCancelable(false);
ad.setPositiveButton( "Load from Cache", new
DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load
cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK,
mycaturl );
}
});
ad.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help.
EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
ad.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to
exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
ad.create();
ad.show();
}
public void alertprep()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if(wv.getSettings().getCacheMode()==WebSettings.LOAD_DEFAULT)
{
String a = "Connection Lost";
String b = "Connection to host was lost. Restart and load
cache or exit.";
alert(a,b);
}
else
if(wv.getSettings().getCacheMode()==WebSettings.LOAD_CACHE_ELSE_NETWORK)
{
String a = "Page Not Cached";
String b = "Page you're trying to view is not yet cached.
Please visit help to learn how to cache.";
alert(a,b);
}
}
public void alert(String a,String b)
{
AlertDialog.Builder ad = new AlertDialog.Builder(
MainActivity.this );
ad.setTitle(a);
ad.setMessage(b);
ad.setIcon(R.drawable.tick);
ad.setCancelable(false);
ad.setPositiveButton( "Restart", new
DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to
restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
ad.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help.
alertprep", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
ad.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to
exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
ad.create();
ad.show();
}
private class wvc extends WebViewClient
{
//when page started loading
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
//circular progress bar open
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
alertprep();
}
else if ( ws.getCacheMode() ==
WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading
cache coz not reachable",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "CACHE
MODE OUT OF BOUNDS!!",
Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() ==
WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(),
"Connection to server established.",
Toast.LENGTH_SHORT).show();
}
}
}
}
//when page finished
@Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE
LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
//when received an error
@Override
public void onReceivedError(WebView view, int errorCode, String
description, String failingUrl)
{
super.onReceivedError(view, errorCode, description,
failingUrl);
//wv.destroy();
wv.loadUrl(helpurl);
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
Toast.makeText(getApplicationContext(), "Page
unavailable", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Page not
cached", Toast.LENGTH_SHORT).show();
}
alertprep();
}
/*url loading
@Override
public boolean shouldOverrideUrlLoading( WebView view, String url )
{
if (url != null && url.endsWith("feedback.htm")) //what to
search in the end of the feedback form
{
Toast.makeText(getApplicationContext(), "URL LOADING
TRUE?!!", Toast.LENGTH_SHORT).show();
Uri uriUrl = Uri.parse(fbackurl);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW,
uriUrl);
startActivity(launchBrowser);
//view.loadUrl(url);
return true;
}
else
{
Toast.makeText(getApplicationContext(), "URL LOADING
FALSE?!!", Toast.LENGTH_SHORT).show();
return false;
}
}*/
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection)
url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in
milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
//options menu inflation
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
// inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//when back button is pressed
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
//when options button is pressed
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
//saving instance state
@Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
//restoring instance state
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Please help, needs urgently. Thanks.
No comments:
Post a Comment