How to link each tabs to Navigation Drawer? - javascript

As I'm new to android I got a small problem where I actually do not know how to do it. Actually I'm looking for a Navigation Drawer menus to link to each tabs. eg: swipe tabs as 'tab1', 'tab2' and 'tab3' and Navigation drawer menu also listed as 'tab1', 'tab2' and ;tab3'. So, when i click 'tab2' from Navigation Drawer it should take me to 'tab2' of swipe tabs. Could someone help me out please.
thanks
//MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this;
list=LoadingContentActivity.list;
Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionar=getSupportActionBar();
actionar.setDisplayHomeAsUpEnabled(true);
actionar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.tab_11) {
startActivity(new Intent(MainActivity.this, FragmentTab1.class));
} else if (menuItem.getItemId() == R.id.tab_22) {
startActivity(new Intent(MainActivity.this, FragmentTab2.class));
} else if (menuItem.getItemId() == R.id.tab_33) {
startActivity(new Intent(MainActivity.this, FragmentTab3.class));
}
return true;
}
});
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new FragmentTab1(), "CALLS");
adapter.addFragment(new FragmentTab2(), "CHATS");
adapter.addFragment(new FragmentTab3(), "CONTACTS");
viewPager.setAdapter(adapter);
}
//TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FragmentTab1();
case 1:
return new FragmentTab2();
case 2:
return new FragmentTab3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}

You don't have to start the same activity again, as this will cause it to be pushed into backstack. I would suggest you simply change the current fragment in ViewPager
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code
mViewPager = (ViewPager) findViewById(R.id.viewpager);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.tab_11) {
mViewPager.setCurrentItem(0);
} else if (menuItem.getItemId() == R.id.tab_22) {
mViewPager.setCurrentItem(1);
} else if (menuItem.getItemId() == R.id.tab_33) {
mViewPager.setCurrentItem(2);
}
mDrawerLayout.closeDrawers();
return true;
}
});
}

Related

How to Open External WebView Links in Browser?

I want to open external webview links in browser so please update my codes. Actually the problem is that my webview contains some google drive links so i want to open all external links in browser and i searches too much about it on the web but i can't find the right solution.
I'm new on android studio so please help me guys.
package com.iaritoppers;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.renderscript.Sampler;
import android.view.KeyEvent;
import android.view.View;
import androidx.appcompat.widget.AppCompatRatingBar;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
private WebView mWebviewPop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppRater.app_launched(this);
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
mwebView.loadUrl("https://www.iaritoppers.com/");
mwebView.setWebViewClient(new MyWebviewClient());
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "abc");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = 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_icar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-e-course-pdf.html");
return true;
}
if (id == R.id.action_share) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "*I recommend you to download this very useful App For Agriculture Students -* ");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
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) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
} else if (id == R.id.nav_icar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-e-course-pdf.html");
} else if (id == R.id.nav_agronomyicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/agronomy-icar-ecourse-pdf-books.html");
} else if (id == R.id.nav_hortiicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/horticulture-icar-ecourse-pdf-books.html");
} else if (id == R.id.nav_dairyicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/dairy-technology-icar-e-course-free-pdf.html");
} else if (id == R.id.nav_tnau) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/tnau-notes-pdf-download-agri-study-material.html");
} else if (id == R.id.nav_angrau) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/angrau-notes-download-angrau-study-material.html");
} else if (id == R.id.nav_syllabus) {
mwebView.loadUrl("https://www.iaritoppers.com/p/agriculture-exams-syllabus.html");
} else if (id == R.id.nav_jrfold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-jrf-old-papers.html");
} else if (id == R.id.nav_bhuold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/bhu-old-paper-ug-and-pg.html");
} else if (id == R.id.nav_iariold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/iari-old-question-papers-download-for.html");
} else if (id == R.id.nav_prepgold) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/07/rajasthan-pre-pg-agriculture-old-question-paper.html");
} else if (id == R.id.nav_afoold) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/ibps-afo-old-question-papers-pdf-download-for-agriculture-field-officer.html");
} else if (id == R.id.nav_agribook) {
mwebView.loadUrl("https://www.iaritoppers.com/p/best-agriculture-books-for-icar-jrf-srf.html");
} else if (id == R.id.nav_entrance) {
mwebView.loadUrl("https://www.iaritoppers.com/search/label/agriculture%20entrance%20exams");
} else if (id == R.id.nav_jobs) {
mwebView.loadUrl("https://www.iaritoppers.com/search/label/Latest%20agriculture%20jobs");
} else if (id == R.id.nav_discussion) {
mwebView.loadUrl("https://www.iaritoppers.com/p/discussion-desk_23.html");
} else if (id == R.id.nav_top) {
mwebView.loadUrl("https://www.iaritoppers.com/p/our-top-contributors.html");
} else if (id == R.id.nav_contact) {
mwebView.loadUrl("https://www.iaritoppers.com/p/about-us.html");
} else if (id == R.id.nav_share) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "*I recommend you to download this very useful App For Agriculture Students -* ");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebviewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar2).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 (mwebView.canGoBack()) {
mwebView.goBack();
} else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I would recommend using a chrome custom tab.
Here is a link to the docs
However, have just pasted the information you need here:
First, add chrome custom tabs to your Gradle file
dependencies {
...
compile 'com.android.support:customtabs:23.3.0'
}
Then create the chrome custom tab and show it:
// Use a CustomTabsIntent.Builder to configure CustomTabsIntent.
// Once ready, call CustomTabsIntent.Builder.build() to create a CustomTabsIntent
// and launch the desired Url with CustomTabsIntent.launchUrl()
String url = ¨https://paul.kinlan.me/¨;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

Using Fused Location Provider for Wikitude

I previously used Android Location Manager to retrieve location. However, when I run wikitude apps, the POIs are loaded but are not displayed. I read a few posts saying that this may caused by basic Location Strategy. Therefore, I decided to use Fused Location Provider. The problem still occur. Please help me anyone
package xyz.arlayer.scratch;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
import java.io.IOException;
public class Augmented extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int WIKITUDE_PERMISSIONS_REQUEST_CAMERA = 2;
private ArchitectView architectView;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_augmented);
this.architectView = this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("AOfmybWCEL410fS81fIe29RwjF2eLJ00DCjmqSl+xZaUQc6E48KtXM9oxnbRayoGTjCzG2hSfq7oxzLDO0K8fVZfNyUs1DnLzm+p4jPSHEotpKJOrMmH8aOJoGLsiFfTcXzJY58Kj/EJt0dOHZvBXz/KBka4EPhvcvoDVq//6FFTYWx0ZWRfX9YCljHdYuEA0smGRDePFWZ3TTxz6sxXRJNfTU2P4aKDSsN1hXCicvw/Yf0cs8/v7xjI7UgOk+HZ+qkU2oDidWOPvPji7cbOhZ6pq3vA35s5aNJQU5t1o2LpaLuJyANaRgS/nGpmTYi/fRB6clGZcwEUgvyEl+OcNFL/7BFJUSJQTBdD6UBXy8Dfioh4mlupKMkIHn1d6nSYgTmu1tMn2MFVKTIL9O1qzopPe9O+J945Pq5NCvXbzaIL+6mn7BO6r+KxEY3XNKnpnmER0lnNxEobpY65Byy1v+oWFSCAi65mzEvGSzhGMMaqzlWHx7vJeaPRSoxqUcokvi8iLfiowRRptkiE+VQmNyb03gEViQd2LaQXl6aY+J2jKTIDXGuOLQ1C6hg0CY1AdKXjaslV4YETAkrpqIGbt+tSEeHPH+dL8gFh4UZe2g6JGQCyR4xRA0CtbAXY3CbSNCNypDox8cqOvwRnl0Jx5iwtuyQ4oOKfA6rV+94ZeLg=");
this.architectView.onCreate(config);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{android.Manifest.permission.CAMERA}, WIKITUDE_PERMISSIONS_REQUEST_CAMERA);
}}
#Override
protected void onPostCreate (Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
architectView.load("file:///android_asset/08_Browsing$Pois_5_Native$Detail$Screen/index.html"); } catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
if (location!=null && Augmented.this.architectView != null ) {
// check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
if ( location.hasAltitude() && location.hasAccuracy() && location.getAccuracy()<7) {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy() );
} else {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000 );
}
}
}
#Override
public void onResume() {
super.onResume();
architectView.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
#Override
protected void onPause() {
architectView.onPause();
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
protected void onDestroy(){
super.onDestroy();
architectView.onDestroy();
}
}

Webview Fragment : Back button and Download Listener?

I make simple webview app. using Webview fragment. App working properly. but problem is i click back button app close down. and second problem is i click on html page link. link not open in default browser. error says webpage not open. i want all tab open in same webview and back button and download link work properly. my code is
MyWebViewFragment.java
package com.example.com;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
MainActivity.java
package com.example.com;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
To open urls in webview use the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.OFF);
webSettings.setSupportMultipleWindows(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheMaxSize(1);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
// webView.setVerticalScrollBarEnabled(false);
// webView.setHorizontalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
// webView.setInitialScale(100);
// webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e("", "shouldOverrideUrlLoading load url" + url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
isLoaded = false;
progressDialog.setMessage("Unknown Error!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
displayProgress(getString(R.string.loading), getString(R.string.loading));
Log.e("onPageStarted",url);
}
public void onPageFinished(WebView view, String url) {
isLoaded = true;
super.onPageFinished(view, url);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
});
web_link = "https://twitter.com";
webView.loadUrl(web_link);
}
public void displayProgress(String title,String mes){
if (progressDialog!=null)
progressDialog.dismiss();
progressDialog = new ProgressDialog(MainActivity.this);
// progressDialog.setTitle(title);
progressDialog.setMessage(mes);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
try {
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
To go back on web view override this method to your activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (web_link!=null && !webView.getUrl().equals(web_link))
webView.goBack();
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.to_exit)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
return super.onKeyDown(keyCode, event);
}

How to dismiss ProgressDialog in Volley and Internet connection error handling

I am trying to create this Volley project as my second activity which fetches a JSON feed from Yahoo Pipe and display in a ListView from here. The code works perfectly fine. However, I have encountered these problems:
When I have not turned the Internet on, the activity displays the loading ProgressDialog. However, pressing the Back button on my emulator or actual device does not dismiss the ProgressDialog. The activity did not respond to the Back action.
I tried this code, but it does not work or maybe I'm not doing it right:
#Override
public void onDestroy() {
super.onDestroy();
dismissPd();
}
private void dismissPd() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
In case of an Internet connection error, how do I display the error message in this activity as a toast?
The following is my code:
public class Trending extends ActionBarActivity {
private String TAG = this.getClass().getSimpleName();
private ListView lstView;
private RequestQueue mRequestQueue;
private ArrayList<NewsModel> arrNews ;
private LayoutInflater lf;
private VolleyAdapter va;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent newActivity3=new Intent();
setResult(RESULT_OK, newActivity3);
lf = LayoutInflater.from(this);
arrNews = new ArrayList<NewsModel>();
va = new VolleyAdapter();
lstView = (ListView) findViewById(R.id.listView);
lstView.setAdapter(va);
mRequestQueue = Volley.newRequestQueue(this);
String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
pd = ProgressDialog.show(this,"Loading...","Please Wait...");
try {
Thread.sleep(2000);
} catch(Exception e) {
}
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
parseJSON(response);
va.notifyDataSetChanged();
pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.getMessage());
}
});
mRequestQueue.add(jr);
}
#Override
public void onDestroy() {
super.onDestroy();
dismissPd();
}
private void dismissPd() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
private void parseJSON(JSONObject json){
try {
JSONObject value = json.getJSONObject("value");
JSONArray items = value.getJSONArray("items");
for (int i=0; i<items.length(); i++) {
JSONObject item = items.getJSONObject(i);
NewsModel nm = new NewsModel();
nm.setTitle(item.optString("title"));
nm.setDescription(item.optString("description"));
nm.setLink(item.optString("link"));
nm.setPubDate(item.optString("pubDate"));
arrNews.add(nm);
}
}
catch(Exception e){
e.printStackTrace();
}
}
class NewsModel {
private String title;
private String link;
private String description;
private String pubDate;
void setTitle(String title) {
this.title = title;
}
void setLink(String link) {
this.link = link;
}
void setDescription(String description) {
this.description = description;
}
void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
String getLink() {
return link;
}
String getDescription() {
return description;
}
String getPubDate() {
return pubDate;
}
String getTitle() {
return title;
}
}
class VolleyAdapter extends BaseAdapter {
#Override
public int getCount() {
return arrNews.size();
}
#Override
public Object getItem(int i) {
return arrNews.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
if (view == null) {
vh = new ViewHolder();
view = lf.inflate(R.layout.row_listview,null);
vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
NewsModel nm = arrNews.get(i);
vh.tvTitle.setText(nm.getTitle());
vh.tvDesc.setText(nm.getDescription());
vh.tvDate.setText(nm.getPubDate());
return view;
}
class ViewHolder {
TextView tvTitle;
TextView tvDesc;
TextView tvDate;
}
}
}
try this one then back button is working while dialog is running
pd = ProgressDialog.show(this,"Loading...","Please Wait...");
pd.setCancelable(true);
By use asynctask you write code like this way
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(ctx, null, "fetching ...");
pd.setCancelable(true);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
//fetch response from internet and process here
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pd.cancel();
//do next action here
super.onPostExecute(result);
}
You have to execute the JSON part of the code in AsyncTask.
Define doInBackground to return a String type. From doInBackground, handle the errors, like internet error or json error and accordingly return a suitable error message "internet error" or "json error".
This error will be available as input to onPostExecute (results). In onPostExecute, you can run a Switch Statement to handle each of the conditions. If "internet error", then pd.dismiss() and do a toast.
For a working version of the code, you can refer here...

Webview Back Button

Wondering how to make webview go back.
Tried putting in the webview back on press but it seems that with my code it's not working. Not sure if i initiated it, still confused about this.
Also is it possible to get rid of scrollbars in webview? i found some posts about it but am still on the fence about how exactly to put it into my code
package com.webapp.area956;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebViewClient yourWebClient = new WebViewClient()
{
// Override page so it's load on my view only
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// This line we let me load only pages inside Firstdroid Webpage
if ( url.contains("area956") == true )
// Load new URL Don't override URL Link
return false;
// Return true to override url loading (In this case do nothing).
return true;
}
};
String url = "http://www.area956.com";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(yourWebClient);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
}
public void onBackPressed (){
if (WebView.canGoBack()) {
WebView.goBack();
}
else {
super.onBackPressed();
finish();
}
}
#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;
}
}
Have webview as a class member
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
Then initialize
view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(yourWebClient);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
Then use onKeyDown
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack();
return true;
}
else
{
finish();
return true;
}
}
You have declared WebView view in onCreate and initialized it there. So it becomes local to onCreate.
Edit:
You can also use onBackPressed as of 2.0
http://android-developers.blogspot.in/2009/12/back-and-other-hard-keys-three-stories.html
public void onBackPressed (){
super.onBackPressed();
if (view.canGoBack()) {
view.goBack();
}
else {
finish();
}
}

Categories