I am trying to use webView to display an HTML file that is on the device and not the internet. I have my html files in the /Download folder. When I launch the application I get the following error:
Webpage not available
The webpage at file:///storage/sdcard0/Download/manuals/test/index4.html might be temporarily down or it may have been moved permanently to a new web address.
I know the file is there but it will not display it.
Here is my code:
package com.asstechmanuals.techmanual;
import java.io.File;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
File fileStandard = new File("/storage/sdcard0/Download/manuals/test/index4.html");
File fileNewStandard = new File("/storage/sdcard0/Download/manuals/test/index4.html");
File fileKitKat = new File("/storage/sdcard0/Download/manuals/test/index4.html");
if(fileStandard.exists())
mWebView.loadUrl("file:///storage/sdcard0/Download/manuals/test/index4.html");
else if(fileNewStandard.exists())
mWebView.loadUrl("file:///storage/sdcard0/Download/manuals/test/index4.html");
else if(fileKitKat.exists())
mWebView.loadUrl("file:///storage/sdcard0/Download/manuals/test/index4.html");
else
mWebView.loadUrl("file:///storage/sdcard0/Download/manuals/test/index4.html");
mWebView.setWebViewClient(new vwClient());
}
private class vwClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
if (url.toLowerCase().contains(".pdf"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(intent);
}
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#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;
}
}
In your manifest xml file, make sure you have permission to read that folder for your app and permission to use internet (even though you actually are not, it is still required).
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Related
I have an Android App which uses WebView to show a map on Open Street Map and few weeks stop working properly.
A few weeks ago when the user tap on show my location on the web page Android shows a prompt to allow the app to load the current position but at the moment just an error is shown: Geolocation error: user denied Geolocation.
I looked here on SO and on Google to find if some part of my code became deprecated or blocked but I didn't find anything useful. The only information I found was about ActionBarActivity but also using AppCompatActivity the problem was the same.
The MVP version of the MainActivity is the following (I deleted other unuseful lines for this example):
package com.vinaysomawat.careerhigh;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
public class MainActivity extends ActionBarActivity {
public String mGeolocationOrigin;
public GeolocationPermissions.Callback mGeolocationCallback;
private static final int REQUEST_FINE_LOCATION=0;
public class GeoWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
}
public class GeoWebChromeClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
String perm = Manifest.permission.ACCESS_FINE_LOCATION;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ContextCompat.checkSelfPermission(MainActivity.this, perm) == PackageManager.PERMISSION_GRANTED) {
// we're on SDK < 23 OR user has already granted permission
callback.invoke(origin, true, false);
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, perm)) {
// ask the user for permission
ActivityCompat.requestPermissions(MainActivity.this, new String[] {perm}, REQUEST_FINE_LOCATION);
// we will use these when user responds
mGeolocationOrigin = origin;
mGeolocationCallback = callback;
}
}}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_FINE_LOCATION:
boolean allow = false;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user has allowed this permission
allow = true;
}
if (mGeolocationCallback != null) {
// call back to web chrome client
mGeolocationCallback.invoke(mGeolocationOrigin, allow, false);
}
break;
}
}
WebView mywebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Hide TopBar
getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebview = (WebView)findViewById(R.id.webView);
WebSettings webSettings = mywebview.getSettings();
// Empty Cache
mywebview.clearCache(true);
// Hide Zoom buttons
mywebview.getSettings().setDisplayZoomControls(false);
mywebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mywebview.getSettings().setBuiltInZoomControls(true);
mywebview.setWebViewClient(new GeoWebViewClient());
// Below required for geolocation
mywebview.getSettings().setJavaScriptEnabled(true);
mywebview.getSettings().setGeolocationEnabled(true);
mywebview.setWebChromeClient(new GeoWebChromeClient());
mywebview.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
{
WebView.HitTestResult result = view.getHitTestResult();
String data = result.getExtra();
Context context = view.getContext();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
context.startActivity(browserIntent);
return false;
}
});
mywebview.loadUrl("https://mycurrentlocation.net/");
}
#Override
public void onBackPressed(){
if(mywebview.canGoBack()) {
mywebview.goBack();
} else
{
super.onBackPressed();
}
}
#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();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
}
When I click the button to show my current position, in Android Studio I get the following log:
E/Resource: printErrorResource, maybe not a error because module has
entative access to resource called by
=android.content.res.HwResourcesImpl.printErrorResource:2634 android.content.res.ResourcesImpl.openRawResource:444
android.content.res.Resources.openRawResource:1418
android.content.res.Resources.openRawResource:1362
android.support.v4.graphics.TypefaceCompatBaseImpl.createFromResourcesFontFile:304
android.support.v4.graphics.TypefaceCompat.createFromResourcesFontFile:232
I/ResourcesImplEx: The apk asset path =
ApkAssets{path=/system/framework/framework-res.apk}
The apk asset path = ApkAssets{path=/system/framework/framework-res-hwext.apk}
The apk asset path = ApkAssets{path=/preas/oversea/overlay/GmsConfigOverlay.apk}
The apk asset path = ApkAssets{path=/preas/oversea/overlay/GmsGsaConfigOverlay.apk}
The apk asset path = ApkAssets{path=/preas/oversea/overlay/GoogleExtServicesConfigOverlay.apk}
The apk asset path = ApkAssets{path=/preas/oversea/overlay/GoogleModuleMetadataConfigOverlay.apk}
The apk asset path = ApkAssets{path=/preas/oversea/overlay/GooglePermissionControllerConfigOverlay.apk}
The apk asset path = ApkAssets{path=/hw_product/overlay/frameworkResOverlay.apk}
The apk asset path = ApkAssets{path=/odm/overlay/frameworkResOverlay.apk}
The apk asset path = ApkAssets{path=/data/app/com.vinaysomawat.careerhigh-3JvsuNOhaJTzUZrEdMaQnA==/base.apk}
I/ResourcesImplEx: The apk asset path =
ApkAssets{path=/data/app/com.google.android.webview-Lw6x1ElnmD4d1UEVSG95iA==/base.apk}
The apk asset path = ApkAssets{path=/data/app/com.google.android.webview-Lw6x1ElnmD4d1UEVSG95iA==/split_config.it.apk}
The apk asset path = ApkAssets{path=/data/app/com.google.android.webview-Lw6x1ElnmD4d1UEVSG95iA==/split_weblayer.apk}
The apk asset path = ApkAssets{path=/data/app/com.google.android.trichromelibrary_489608833-ndmJcgRaxXQPmZ7r_KqT-w==/base.apk}
and then this log is shown (I think this is the error banner that say that can't load the position):
D/HiTouch_PressGestureDetector: onAttached,
package=com.vinaysomawat.careerhigh, windowType=2,
mHiTouchRestricted=false D/mali_winsys: EGLint
new_window_surface(egl_winsys_display *, void *, EGLSurface,
EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
Yes. I had a similar problem. Location permissions for an android webview and geolocation are no longer handled by the webChromeClient. They are now handled in the same way as an Android native app. I used the following as a guide and it worked well.
https://developer.android.com/training/location/permissions
I am working on a project in Android Studio. My MainActivity shows the Actionbar. I created a new empty activity named Teachers. It shows the Actionbar when it's empty. I then created a webview. But when I input this webview code on Teachers activity, the Actionbar is not shown in the app (even though the webview works properly).
package com.codepade.shohel.eee7brur;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Teachers extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teachers);
webView = (WebView) findViewById(R.id.teachersweb);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/teachers/index.html");
webView.setWebViewClient(new WebViewClient());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack() == true){
webView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
in your Activity you can try getActionBar().show();
I was working in android studio 1.3.2 for some days, I am very much new to android development. Here I need to check the internet connection, if internet is there I need to display a webpage, and if internet is not there, I need to display an alert box saying 'no internet connection found'. This is the code I have done so far.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.activity_main);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String url = "http://facebook.com";
webView.getSettings().setJavaScriptEnabled(true);
if(isConnectingToInternet(getApplicationContext())) {
webView.loadUrl(url);
}else{
// show alert
Toast.makeText(getApplicationContext(), "no internet", Toast.LENGTH_LONG).show();
}
}
private boolean isConnectingToInternet(Context applicationContext){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
Toast.makeText(getApplicationContext(), "no internet", Toast.LENGTH_LONG).show();
return false;
} else
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#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) {
// 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);
}
}
But the alert is not showing when there is no internet connection.
I have enabled
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in AndroidManifest.xml. I am stucked here, I don't know what to do next. I googled alot, but couldn't find an answer. Can anyone please help me?
put this in your android manifest
<uses-permission android:name="android.permission.INTERNET" />
check internet connect if connected load url in your webview else show alert.
EDIT: your onCreate() should look like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.sufi_boutique);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String url = "http://facebook.com";
webView.getSettings().setJavaScriptEnabled(true);
if(isConnectingToInternet(getApplicationContext())) {
webView.loadUrl(url);
}else{
// show alert
Toast.makeText(getApplicationContext(),"no internet",Toast.LENGTH_LONG).show();
}
}
make sure you have added internet permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
I'm trying to make an app that I can get a simple implementation of in app purchases. I've been falling this guide http://www.techotopia.com/index.php/Integrating_Google_Play_In-app_Billing_into_an_Android_Application_%E2%80%93_A_Tutorial
but it's fraught with probably outdated information and neglects to include all the names of the packages you need to download from the SDK manager.
The main errors I had from this program were seemingly reference errors like I had not imported a certain library or compatibility files were missing. I managed to resolve all of them in eclipse and there are no errors when I run the code but trying it on a device or in the VM, the app crashes when I try to run it there.
I excluded the key you need for the google play connection for obvious reasons.
package com.a.inappbilling;
import com.a.inappbilling.util.IabHelper;
import com.a.inappbilling.util.IabResult;
import com.a.inappbilling.util.Inventory;
import com.a.inappbilling.util.Purchase;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.content.Intent;
import android.util.Log;
public class InAppBillingActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_app_billing);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.in_app_billing, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_in_app_billing,
container, false);
return rootView;
}
}
private Button clickButton;
private Button buyButton;
#Override
protected void onStart() {
super.onStart();
buyButton = (Button)findViewById(R.id.buyButton);
clickButton = (Button)findViewById(R.id.clickButton);
clickButton.setEnabled(false);
String base64EncodedPublicKey =
"key here";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " +
result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void buttonClicked (View view)
{
clickButton.setEnabled(false);
buyButton.setEnabled(true);
}
private static final String TAG = "com.a.inappbilling";
IabHelper mHelper;
}
Add permission to your Manifest file
<uses-permission android:name="com.android.vending.BILLING" />
also add to your Manifest file under the Application node
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Also just verify you have added InAppBillingActivity.java to your Manifest file.
I am fairly new to java and I have been trying to learn, so I made a webview app for my website that I have published and a few people have reported an error as listed below:
java.lang.NullPointerException
at com.alexriggs.android.mafiastreetwars.MafiaStreetWarsActivity$MyWebViewClient.shouldOverrideUrlLoading(MafiaStreetWarsActivity.java:87)
at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:227)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:334)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3704)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
at dalvik.system.NativeStart.main(Native Method)
No I know enough to know that java.lang.NullPointerException means that a variable is empty but being used as not empty. And after looking back at my code, it should never be empty and I cannot reproduce it. So here is my code, can anyone figure out what is wrong? And please remember that I am new to Java, so please use as much detail as possible!
package com.alexriggs.android.mafiastreetwars;
import com.alexriggs.android.mafiastreetwars.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MafiaStreetWarsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exit:{
Toast.makeText(this, "Thanks For playing Mafia Street Wars!", Toast.LENGTH_LONG).show();
finish();
break;
}
case R.id.select_and_copy:
{
Toast.makeText(getApplicationContext(), "Select Text by dragging over the text you want to copy.", Toast.LENGTH_LONG).show();
selectAndCopyText(myWebView);
return true;
}
}
return true;
}
private void selectAndCopyText(WebView view) {
try
{
KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(view);
}
catch (Exception e)
{
Log.e("dd", "Exception in emulateShiftHeld()", e);
}
}
final Activity activity = this;
WebView myWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Remember...");
alertDialog.setMessage("This app is just for mobile access. This game is meant to be played on the computer at MafiaStreetWars.com");
alertDialog.setButton("Thanks for the reminder!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.setIcon(R.drawable.icon);
alertDialog.show();
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setPluginsEnabled(true);
Toast.makeText(getApplicationContext(), "Page is loading... Please wait!", Toast.LENGTH_LONG).show();
myWebView.loadUrl("http://mafiastreetwars.com/?pk_campaign=Android&pk_kwd=MainApp");
}
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("mafiastreetwars.com")) {
return false;
}
// Otherwise, give the default behavior (open in browser)
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
It's probably due to Uri.parse(url).getHost() returning null. Check this before you call equals().
Line in question if (Uri.parse(url).getHost().equals("mafiastreetwars.com")) {
Looks like your url is null, or the parse result is null but that is less likely. Check to see if things are null before using them!
I suggest you to do it a little bit more nullsave:
if (url==null)
return false;
Uri lUri = Uri.parse(url);
if ("mafiastreetwars.com".equals(lUri.getHost())) {
return false;
}
that solves your technical problem but maybe not youre business case.