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.
Related
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
}
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
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.
I am trying to show web view with navigation drawer in android. I am also implementing this but web view listener is not working.
This is my main Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerLayout = navigationView.getHeaderView(0);
lv = (ListView) headerLayout.findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, prgmNameList, prgmImages));
Button button = (Button) findViewById(R.id.btbn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_SHORT).show();
}
});
webview = (WebView) findViewById(R.id.contaner);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(MainActivity.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " + url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("https://www.google.co.in/maps?source=tldsi&hl=en");
}
#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;
}
And this is layout file
<?xml version="1.0" encoding="utf-8"?>
<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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/contaner"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
<Button
android:id="#+id/btbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
Any help, suggestion, tutorials would be highly appreciated. Thank you....
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//This is code for Enable Javascript
superWebView.getSettings().setJavaScriptEnabled(true);
//This is code for Enable Webclient to open webview without application
superWebView.setWebViewClient(new WebViewClient());
//This is code for Webchrome
superWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
getSupportActionBar().setTitle(title);
}
});
............................................
..........Same as Above Code................
............................................
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
//THis show web view with Navigation Drawer link as Webview
superWebView.loadUrl("http://www.google.com");
} 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;
}
check it official doc of web vie
https://developer.android.com/guide/webapps/webview.html
I have a problem with the navigation drawer. I want to know how to display recyclerview when the user clicks on different element of each menu.
Here are some source code and an illustrative capture
N.B: different menu items ("Accueil, Contacts Staff, etc ...") are in an .xml file in the layout.
MainActiviy.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setupWindowAnimations();
//définir la toolbr en tant qu'actionbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.setDrawerListener(drawerToggle);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
//on remplit notre viewpager, comme à notre habitude
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return RecyclerViewFragment.newInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
#Override
public int getCount() {
return 1;
}
});
//indique au tablayout quel est le viewpager à écouter
tabLayout.setupWithViewPager(viewPager);
}
private void setupWindowAnimations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Explode explode = new Explode();
getWindow().setExitTransition(explode);
Fade fade = new Fade();
getWindow().setReenterTransition(fade);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#OnClick(R.id.fab)
public void onFabClick() {
Snackbar.make(fab, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).show();
}
}
Sample source code for you
public class NavActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
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);
}
#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 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;
}
}
Hope this helps you
Not understand exactly what you want. Where do you want to display recycler view? You already have OnNavigationItemSelectedListener, just check which menu you have clicked and do what you want:
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.contact:
// do anything you want, ex
showContactList();
break;
}
the function to show your contact list
private void showContactList(){
List<Contact> data = getYourDataSomeHow();
yourAdapter.setData(data);
yourRecyclerView.setAdapter(yourAdapter);
}