How to show ProgssBar when internet connection not avaliable? - android

I am working an Android app. When internet connection is not avaliable app closes. I have used few method for solve this problem, but i can't. I have searched in Google more forums, bur can't find. Maybe you can solve this problem.
In app uses Webview and Jsoup parser. I give you all MainActivity code for good understanting.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
webview= (WebView) findViewById(R.id.webview1);
webview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new MyAsynTask().execute(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
new MyAsynTask().execute(this.url);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_camera) {
url="http://hut.az/arenda-kvartir/";
webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new MyAsynTask().execute(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
new MyAsynTask().execute(this.url);
} else if (id == R.id.nav_gallery) {
url="http://hut.az/prodaja-kvartir/";
webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new MyAsynTask().execute(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
new MyAsynTask().execute(this.url);
} else if (id == R.id.nav_slideshow) {
url="http://hut.az/novostroyki/";
webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new MyAsynTask().execute(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
new MyAsynTask().execute(this.url);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyAsynTask extends AsyncTask<String, Void, Document > {
#Override
protected Document doInBackground(String... urls) {
Document document = null;
try {
document= Jsoup.connect(urls[0]).get();
document.getElementsByClass("header1").remove();
document.getElementsByClass("topbar clearfix").remove();
document.getElementsByClass("mapandslider").remove();
document.select("div#right_sidebar").remove();
document.select("div#left_sidebar").remove();
document.getElementsByClass("footer1").remove();
document.getElementsByClass("copyright").remove();
} catch (IOException e) {
e.printStackTrace();
this.ShowMess();
}
return document;
}
public void ShowMess(){
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Internet Baglantisi Yoxdur !");
progressDialog.setMessage("Zəhmət olmasa gözləyin...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Yüklənir");
progressDialog.setMessage("Zəhmət olmasa gözləyin...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
webview.loadDataWithBaseURL(url,document.toString(),"text/html","utf-8","");
progressDialog.dismiss();
}
}
}

use following method:
private boolean checkNetwork() {
boolean wifiDataAvailable = false;
boolean mobileDataAvailable = false;
ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo = conManager.getAllNetworkInfo();
for (NetworkInfo netInfo : networkInfo) {
if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
if (netInfo.isConnected())
wifiDataAvailable = true;
if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
if (netInfo.isConnected())
mobileDataAvailable = true;
}
return wifiDataAvailable || mobileDataAvailable;
}
where you want to show progressbar.
if(!checkNetwork()){
show progressbar or you want to show toast also like no internet connection avilable please try again
}
else {
your task you want
}

Related

how could I refresh a webview?

so i made a website which could be turned into mobile app simply by using webview. when the first time i install the apk, it work perfectly well but the problem is after that, the web is just static or it's not loaded anymore.
it just open up the same content like the first time i install it even though i already change the whole website. i don't know if the problem was with the webview or with the android.
i already try made a auto refresh/autoreload function in php but it only work in mobile browser and didn't work in my app...
anyone know any solution?
since i'm a newbie in android developping i'll put the whole code of my main activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//WebView
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mwebView.getSettings().setAppCacheEnabled(true);
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
mwebView.loadUrl("http://192.168.94.2/autorefresh/");
//force links open in webview only
mwebView.setWebViewClient(new MyWebviewClient());
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.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();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
mwebView.loadUrl("http://192.168.94.2/ee1/");
}
if (id == R.id.nav_kolam) {
mwebView.loadUrl("http://192.168.94.2/ee1/listkolam.php");
}
if (id == R.id.nav_pantai) {
mwebView.loadUrl("http://192.168.94.2/ee1/listpantai.php");
}
if (id == R.id.nav_transaksi) {
System.exit(0);
}
if (id == R.id.nav_about) {
System.exit(0);
}
if (id == R.id.nav_keluar) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//bikin progress dialog
private class MyWebviewClient extends WebViewClient {
//ProgressDialogue
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("192.168.94.2")) {
//open url contents in webview
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd=new ProgressDialog(MainActivity.this);
pd.setTitle("Mohon Tunggu Sebentar");
pd.setMessage("Website Loading..");
pd.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
super.onPageFinished(view, url);
}
}
//bikin tombol back halaman
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebView.canGoBack()) {
mwebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}}
i'm using native php
The webView caches all the Contents of the Site , so that it doesn't need to download images etc.
For you to get the updations you need to maintain versioning your files and have a cache-control = max-age on yout index.html file
mwebView.loadUrl("about:blank");
mwebView.loadUrl("http://192.168.94.2/ee1/");
Load blank page before loading any new url.
So add mwebView.loadUrl("about:blank"); before all your if-else cases.
May this help!
webView.loadUrl("javascript:window.location.reload(true)");
This may help to reload the webview. Thanks

Android Webview crashes on android 4.4 while opening external url

I am developing an application where I am using a webview. Everything is working fine but when I try to open external links inside webview it either freezes or crashes.This happens on android 4.4 and below but works well on android 5.0 and above.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
///initialize webview
private WebView mwebview;
ProgressBar bar;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mwebview = (WebView) findViewById(R.id.myWebview);
bar = (ProgressBar) findViewById(R.id.progressBar2);
WebSettings webSettings = mwebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mwebview.loadUrl("http://stalls.co.ke/shopping");
// improve webview perfomance
mwebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
if (Build.VERSION.SDK_INT >= 19) {
mwebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mwebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mwebview.getSettings().setAppCacheEnabled(true);
mwebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
//force links to open in webview only
mwebview.setWebViewClient(new MyWebViewClient());
// 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() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
mwebview.loadUrl("http://stalls.co.ke/shopping");
} else if (id == R.id.nav_gifts) {
mwebview.loadUrl("http://stalls.co.ke/gifts-coupons");
} else if (id == R.id.nav_men) {
mwebview.loadUrl("http://stalls.co.ke/stallswear-men");
} else if (id == R.id.nav_women) {
mwebview.loadUrl("http://stalls.co.ke/stallswear-women");
} else if (id == R.id.nav_kids) {
mwebview.loadUrl("http://stalls.co.ke/stallswear-kids-baby");
} else if (id == R.id.nav_men_cosmetics) {
mwebview.loadUrl("http://stalls.co.ke/copy-of-stalls-cosmetics");
} else if (id == R.id.nav_women_cosmetics) {
mwebview.loadUrl("http://stalls.co.ke/copy-of-men-footwear");
} else if (id == R.id.nav_kids_cosmetics) {
mwebview.loadUrl("http://stalls.co.ke/copy-of-stalls-cosmetics");
} else if (id == R.id.nav_homes) {
mwebview.loadUrl("http://stalls.co.ke/home-kitchen-products");
} else if (id == R.id.nav_garden) {
mwebview.loadUrl("http://stalls.co.ke/garden-products");
} else if (id == R.id.nav_smarthomes) {
mwebview.loadUrl("http://stalls.co.ke/smart-home-products");
} else if (id == R.id.nav_eatery) {
mwebview.loadUrl("http://stalls.co.ke/stallseatery");
} else if (id == R.id.nav_customer_service) {
mwebview.loadUrl("http://stalls.co.ke/help");
} else if (id == R.id.nav_about_us) {
mwebview.loadUrl("http://stalls.co.ke/about-us");
} else if (id == R.id.nav_kijo) {
mwebview.loadUrl("http://stalls.co.ke/house-of-kinjo");
} else if (id == R.id.nav_Airi) {
mwebview.loadUrl("http://stalls.co.ke/Airi");
} else if (id == R.id.nav_mamapeter) {
mwebview.loadUrl("http://stalls.co.ke/house-of-kinjo");
} else if (id == R.id.nav_swahili) {
mwebview.loadUrl("http://stalls.co.ke/swahili-princess");
} else if (id == R.id.nav_allstalls) {
mwebview.loadUrl("http://stalls.co.ke/kenyan-stores");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#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();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#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.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
// go to previous page when back button is pressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebview.canGoBack()) {
mwebview.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
bar.setVisibility(view.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mwebview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(request.getUrl().toString());
}
return false;
}
});
} else {
mwebview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
return false;
}
}
}
This is my MainActivity.java file, I would like to know why this is happening.
try using WebChromeClient; instead of WebViewClient; see if it works.

Android Studio MainActivity.java:: error: '}' expected

I am new to Android development, When Android Studio in "Main Activity" class is compiled I get the Error error '}' expected android
public class ShowWebView extends Activity {
//private Button button;
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private static final int FILECHOOSER_RESULTCODE = 2888;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private View adview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//////////////////////////SETUP Web Link//////////////////////////////////
String webViewUrl = "http://doblist.com/";
//Get webview
webView = (WebView) findViewById(R.id.webView1);
//startWebView("http://50.73.3.244/Mobile/");
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//Other webview settings
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
//Load url in webview
webView.loadUrl(webViewUrl);
// Define Webview manage classes
startWebView();
}
private void startWebView() {
//Create new webview Client to show progress dialog
//Called When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are open in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Check if Url contains ExternalLinks string in url
// then open url in new browser
// else all webview links will open in webview browser
if(url.contains("3j3j3j2i3j2i3ji2"))
{
// Could be cleverer and use a regex
//Open links in new browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// Here we can open new activity
return true;
} else {
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
// if url contains string androidexample
// Then show progress Dialog
if (progressDialog == null && url.contains("lol")
) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(ShowWebView.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
try{
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// implement WebChromeClient inner class
// we will define openFileChooser for select file from camera
webView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
/**updated, out of the IF **/
mUploadMessage = uploadMsg;
/**updated, out of the IF **/
try{
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file); // save to the private variable
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
// captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Camera Exception:"+e, Toast.LENGTH_LONG).show();
}
//}
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
/** Added code to clarify chooser. **/
//The webPage has 2 filechoosers and will send a console message informing what action to perform, taking a photo or updating the file
public boolean onConsoleMessage(ConsoleMessage cm) {
onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
//Toast.makeText(getBaseContext(), cm.message()+" :message", Toast.LENGTH_LONG).show();
return true;
}
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
//Log.d("androidruntime", "Per c�nsola: " + message);
//Toast.makeText(getBaseContext(), message+":message", Toast.LENGTH_LONG).show();
//if(message.endsWith("foto")){ boolFileChooser= true; }
//else if(message.endsWith("pujada")){ boolFileChooser= false; }
}
/** Added code to clarify chooser. **/
});
}
// Return here when file selected from camera or from SDcard
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == this.mUploadMessage) {
return;
}
Uri result=null;
try{
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "activity :"+e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
// Open previous opened link from history on webview when back button pressed
#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();
}
}
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is My MainActivity class is compiled but I get the Error error '}' expected android
You are missing a } at the end of the class.
Basically you forgot to close your ShowWebView class. All you need to do is add a } in the end. Rest of code looks fine to me.
To my surprise, this error should be detected by your IDE (Android Studio) which should be looking something like this.

How to stop swipetorefresh progressbar in webview?

I'm new with Android development. I got trouble using SwipeToRefresh option in WebView. I'm trying to solve it from a mounth now and after trying several codes, it's not working. Also Youtube video is not playing in full screen from the WebView...
Here's my question: How to hide SwipeToRefresh ProgressBar and stop running?
Here is my MainActivity class:
public class WebViewActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private WebView myWebView;
private SwipeRefreshLayout mSwipeRefreshLayout;
//HTML5 video
private View mCustomView;
private int mOriginalSystemUiVisibility;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
setContentView(R.layout.activity_web_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-App Id");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//WebView
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshlayout);
myWebView = (WebView) findViewById(R.id.webview);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
myWebViewSettings();
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
myWebView.loadUrl("http://www.youtube.com");
//force links open in webview only
myWebView.reload(); // refreshes the WebView
}
});
myWebView.setWebViewClient(new MyWebViewClient());
}
#SuppressLint("SetJavaScriptEnabled")
#SuppressWarnings("deprecation")
private void myWebViewSettings() {
// set javascript and zoom and some other settings
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDisplayZoomControls(false);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
// enable all plugins (flash)
myWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.web_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Subject more ");
startActivity(Intent.createChooser(shareIntent, "Share Via"));
break;
default:
break;
}
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.facebook) {
// Handle the camera action
myWebView.loadUrl("http://www.facebook.com");
} else if (id == R.id.google) {
myWebView.loadUrl("http://www.google.com");
}
//share in navigation
else if (id == R.id.share) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Androidwebview");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Try out this cool app www.applink.com");
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
//rate us in navigation
else if (id == R.id.rateus) {
String str = getPackageName();
try
{
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=" + str)));
}
catch (ActivityNotFoundException localActivityNotFoundException)
{
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=" + str)));
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
// show error if no network
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
view.loadUrl("file:///android_asset/error.png");
}
// load from
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
//progress bar
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progress1).setVisibility(View.GONE);
}
}
//goto previous page when pressing back button
#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 fires when a notification is opened by tapping on it or one is received while the app is running.
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
#Override
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
try {
if (additionalData != null) {
if (additionalData.has("actionSelected"))
Log.d("OneSignalExample", "OneSignal notification button with id " + additionalData.getString("actionSelected") + " pressed");
Log.d("OneSignalExample", "Full additionalData:\n" + additionalData.toString());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
Here is XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/content_web_view"
android:layout_width="fill_parent"
android:layout_above="#+id/adView"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.androidwebview.WebViewActivity"
tools:showIn="#layout/app_bar_web_view">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"
android:layout_above="#+id/adView"
android:visible="false"
android:layout_alignParentLeft="true" />``
</android.support.v4.widget.SwipeRefreshLayout>
<FrameLayout
android:id="#+id/customViewContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"/>
<ProgressBar
android:id="#+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="80dp"
android:layout_height="80dp" />
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
I had the same problem and i found the question in another thread:
final SwipeRefreshLayout swipeLayout =
(SwipeRefreshLayout)this.findViewById(R.id.swipeToRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
myWebView.reload(); // refreshes the WebView
if (null != swipeLayout) {
swipeLayout.setRefreshing(false);
}
}
});

Failed to convert value of type java.util.HashMap to boolean

I'm trying to detect the connection state of my app, but this is the Error am facing:
Failed to convert value of type java.util.HashMap to boolean
I am using Firebase. The error is on line:
boolean connected = dataSnapshot.getValue(Boolean.class);
So the Error comes in the OnDataFinishedLoading() method . Data was coming at first, but now I just want to detect the apps network connection. Below is my code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static String KEY_HEADLINES="headlines";
public static String KEY_DETAILS="details";
// private static final String TAG = "Ask Doctor App";
ProgressBar pb;
public List<NewsModel> newslist;
public NewsAdapter2 adapter;
private RecyclerView mRecyclerView;
private DatabaseReference mRef;
ImageView image_news;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call the array list
newslist = new ArrayList<NewsModel>();
pb = (ProgressBar) findViewById(R.id.progressBarNews);
image_news =(ImageView) findViewById(R.id.image_news);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Enabling offline capabilities
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// firebase initialisation......
mRef = FirebaseDatabase.getInstance().getReference("News");
// keep my data synced
mRef.keepSynced(true);
OnDataFinishedLoading();
// load data
//declare the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo netInfo = cm.getActiveNetworkInfo();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* if (isOnline()) {
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();
} else {
Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
.setAction("", null).show();
}
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();*/
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void OnDataFinishedLoading(){
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
boolean connected = dataSnapshot.getValue(Boolean.class);
if(connected) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void LoadData (DataSnapshot dataSnapshot){
System.out.println(dataSnapshot.getValue());
NewsModel news_model =dataSnapshot.getValue(NewsModel.class);
newslist.add(news_model);
adapter = new NewsAdapter2(MainActivity.this, newslist);
mRecyclerView.setAdapter(adapter);
}
/* protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
*/
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.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);
}*/
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.hospitals) {
i = new Intent(MainActivity.this, HealthCentres.class);
startActivity(i);
} else if (id == R.id.doctors) {
i = new Intent(MainActivity.this, Doctors.class);
startActivity(i);
} /*else if (id == R.id.location) {
i = new Intent(MainActivity.this, Location.class);
startActivity(i);
} */else if (id == R.id.tips) {
i = new Intent(MainActivity.this, Tips.class);
startActivity(i);
} /*else if (id == R.id.faq) {
}
*/
/*
else if (id == R.id.suggestions) {
}
*/
else if (id == R.id.contacts) {
i= new Intent(MainActivity.this, ContactUs.class);
startActivity(i);
}
/*
else if (id == R.id.settings) {
}
*/
else if (id == R.id.about) {
i = new Intent(MainActivity.this, AboutUs.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Ok, so the core problem you're having is that Firebase is returning a Map, not a Boolean. That's because of the way you have this configured--every time a child is added, you try to look at the DataSnapshot (that's what the listener you setup does), and tries to get a Boolean value out. However, the Snapshot is the child added to the database (and not a boolean) so instead you get a map out.
If all you want to do is verify that a child was added successfully, I'd do the following:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object value = dataSnapshot.getValue();
if(value != null) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
However, this isn't really going to solve your network connectivity problem. It'll just do stuff whenever a non-null child gets added to the firebase object, which could happen frequently. Also in LoadData, you don't check to make sure that the object passed in isn't null.

Categories

Resources