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>
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();
First of all I would like to say that I'm total noob when it comes to Android and Java development but I have managed to run the following code and it lauches my website. Sweet.
Here is the code:
package se.madesolutions.cmok;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.loadUrl("http://mywebsite.com");
mywebView.setWebViewClient(new WebViewClient());
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onBackPressed() {
if(mywebView.canGoBack()){
mywebView.goBack();
} else {
super.onBackPressed();
}
}
#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);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://se.madesolutions.cmok/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://se.madesolutions.cmok/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
What i have done is that I have implemented Facebook login on my website where users can login easy. This works great when I test on Desktop computer but when trying to login through the Android app which launches same website i'm just getting a blank webpage after login with Facebook.
Does anyone have any ideas how to solve this? All help appriciated.
mywebView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getContext(), description, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
});
mywebView.loadUrl("http://mywebsite.com");
Try This
hi i have same problem and i have solved.This happened due to loading your activity.May be you used some background with heavy images.
Try this way
Add this theme in your manifest file that white screen activity
android:theme="#android:style/Theme.Translucent.NoTitleBar"
Thanks hope this will help you.
#mansur try using facebook Sdk which is very easy to login and fetch data from facebook related to that user
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 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" />