Webview to load while slashscreen is on - java

Quite new to android studio but i'm facing a problem where my WebView is taking too long to load, so i've created a splashscreen for 4 seconds and plan to cover the loading using this splash screen. But I dont really know how to let it overlap so the WebView can load behind the splashscreen.
the java for my splash screen
public class MainActivity extends ActionBarActivity {
private static int SPLASH_TIME_OUT = 4000;
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run(){
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
}
}
then i also have a bottombar that navigates to the first framgment with the webview and the java are as below
public class HomeActivity extends ActionBarActivity {
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
mBottomBar = BottomBar.attach(this,savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.menu_main,new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int i) {
if(i==R.id.Bottombaritemone) {
HomeFragment f = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f).commit();
}
else if(i==R.id.Bottombaritemtwo)
{
SearchFragment f =new SearchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i==R.id.Bottombaritemthree)
{
AccountFragment f =new AccountFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int i) {
}
});
mBottomBar.mapColorForTab(0,"#F2F2F2");
mBottomBar.mapColorForTab(1,"#F2F2F2");
mBottomBar.mapColorForTab(2,"#F2F2F2");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
and finally the java for my webview in the first HomeFragment
public class HomeFragment extends Fragment {
WebView my2WebView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home,container,false);
getLoaderManager();
my2WebView = (WebView) view.findViewById(R.id.webView1);
WebSettings webSettings = my2WebView.getSettings();
my2WebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setEnableSmoothTransition(true);
webSettings.setJavaScriptEnabled(true);
webSettings.getLoadsImagesAutomatically();
my2WebView.loadUrl("http://www.fidellaglobal.com/feed");
my2WebView.setWebViewClient(new WebViewClient());
return view;
}
so what can i do to making the webview in the first fragment to load when the splashscreen is on ? thank you :)

Initially set your WebView visibility invisible inside your layout file. Add you WebView in same screen which have delay Handler.
new Handler().postDelayed(new Runnable() {
#Override
public void run(){
// Make your webview visible
mWebView.setVisibility(View.VISIBLE);
}
},SPLASH_TIME_OUT);

Related

How to close Unity without closing the entire app when changing fragments in Android Studio?

I have an app that the user can go through different fragments using BottomNavigationView and one of those fragments is a Unity3D application. So when i open the Unity fragment it works but when i open another fragment and open the Unity fragment back it crashes how do i fix this here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView mBottomNavigationView;
NavController mNavController;
NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
private boolean doubleBackToExitPressedOnce ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_SHORT).show();
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
//Toast.makeText(getApplicationContext(), mDestination.toString(),Toast.LENGTH_SHORT).show();
if (doubleBackToExitPressedOnce) {
getSupportFragmentManager().popBackStackImmediate();
mNavController.navigate(mDestination.getId());
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
UnityMapFragment
public class MapFragment extends Fragment{
protected UnityPlayer mUnityPlayer;
FrameLayout frameLayoutForUnity;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mUnityPlayer = new UnityPlayer(getActivity());
View view = inflater.inflate(R.layout.fragment_map, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.frameLayoutForUnity);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
#Override
public void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override
public void onResume() {
super.onResume();
mUnityPlayer.resume();
}
// Quit Unity
#Override
public void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
So I managed to make a solution for this problem don't know if its good to make it this way or not but what i did was I instantiate the UnityPlayer in my MainActivity and in my fragment i call upon the UnityPlayer that was instatiated in my Main Activity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public BottomNavigationView mBottomNavigationView;
public NavController mNavController;
public NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
int onBackTimes = 0;
public UnityPlayer mUnityPlayer; <----Call unity player
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(this); <----UNITY PLAYER HERE
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
onBackTimes +=1;
if(onBackTimes>1){
LoginActivity.close.finish();
finish();
}
else{
getSupportFragmentManager().popBackStackImmediate();
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
mNavController.navigate(mDestination.getId());
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onBackTimes=0;
}
}, 2000);
}
#Override
protected void onStop() {
super.onStop();
}
//UNITY STUFF OVER HERE
#Override
protected void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
}
UnityMapFragment
public class MapFragment extends Fragment{
private MainActivity mUnityMainActivity;
private UnityPlayer mUnityPlayer;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this code calls the UNITYPLAYER from MainActivity and return it here
mUnityMainActivity = (MainActivity) getActivity();
View unityPlayViewer = mUnityMainActivity.mUnityPlayer.getView();
mUnityMainActivity.mUnityPlayer.requestFocus();
mUnityMainActivity.mUnityPlayer.windowFocusChanged(true);
return unityPlayViewer;
}
/** FOR UNITY **/
#Override
public void onPause() {
super.onPause();
mUnityMainActivity.mUnityPlayer.pause();
}
// Resume Unity
#Override public void onResume()
{
super.onResume();
mUnityMainActivity.mUnityPlayer.resume();
}
I don't know why i have to include the OnPause, OnResume etc on both file but if one of them doesn't have it it'll crash.
The problem is, a new UnityPlayer is being created every-time we switch to the unity fragment and this crashes the app. So we need to create the UnityPlayer only for the first time or only when the player has been stopped. This works on my side.
In the UnityFragment class, my global variables :
protected UnityPlayer mUnityPlayer;
private View view;
private FrameLayout frameLayoutForUnity;
In onCreate a new UnityPlayer is created, which is called only for the first time :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(getActivity()); // create Unity Player
}
In onCreateView we refresh the view for UnityPlayer :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(mUnityPlayer.getParent() != null){
((ViewGroup)mUnityPlayer.getParent()).removeAllViews();
}
view = inflater.inflate(R.layout.fragment_unity, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.unityFragmentLayout);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
Rest remains same. There could be better solutions than this. Cheers :)

How can i load WebView URL in fragment from another AppCompatActivity class

I am creating project for "Drawer with Swipe Tab". There i used a webview in fragment and i want to load Webview URL from Another AppCompatActivity. How can i do it?
Fragment Class:
public class SocialFragment extends Fragment {
ProgressBar pb_per;
public WebView mWebView;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.social_layout, container, false);
pb_per = (ProgressBar) view.findViewById(R.id.progressBar_book1);
mWebView = (WebView) view.findViewById(R.id.web_book1); //This is the id you gave for webview
//--------------------------- to over ride keyboard error ------(1)
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
//--------------------------------------------------
mWebView.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
mWebView.setBackgroundColor(Color.parseColor("#FFFFFF"));
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(false);
// Load URL
mWebView.loadUrl("http://www.twitter.com");
mWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return view;
}
//===================================================================
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
pb_per.setVisibility(View.VISIBLE);
// multi_per.setVisibility(ProgressBar.GONE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pb_per.setVisibility(View.GONE);
// multi_per.setVisibility(ProgressBar.VISIBLE);
}
}
}
TabFragment.Java Class
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to Position .
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
// This method returns the title of the tab according to the position.
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Facebook";
case 1 :
return "Twitter";
}
return null;
}
}
}
AppCompatActivity class:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the DrawerLayout and NavigationView
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
// Lets inflate the very first fragment
// Here , we are inflating the TabFragment as the first Fragment
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
// Setup click events on the Navigation View Items.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
//###############################From Here I Call WEBVIEW URL #######################
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
}
return false;
}
});
// Setup Drawer Toggle of the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
I had Tried #cprakashagr Given Solutation but getting error See below Image
See Error ScreenShot
Use localBroadCastManager
WebViewHavingActivity
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mWebViewLoader);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mWebViewLoader) to receive Intents
// with actions named "WebView".
LocalBroadcastManager.getInstance(this).registerReceiver(
mWebViewLoader, new IntentFilter("WebView"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "WebView" is broadcasted.
private BroadcastReceiver mWebViewLoader = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("http://google.com");
}
});
}
};
CallingActivity
LocalBroadcastManager.getInstance(JobDetailScreen.this).sendBroadcast(new Intent("WebView"));
This Work for me Thanks For trying me to Help
SocialFragment.mWebView.post(new Runnable() {
public void run() {
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
});

Activity is not an enclosing class in Android Studio

I am New to Android. I Have Created Tab using android.support.v4.view.ViewPager. When i trying to get data from server using Json Request it give me the Error
AccountActivity is not an enclosing class.
please Any Help will be Appreciated
TAb1.java
public class Tab1 extends Fragment {
private ProgressDialog pDialog;
private UserAddress userAddress;
private TextView txtResponsec;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new LoadUserAddress().execute();
}
class LoadUserAddress extends AsyncTask<String,String,String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONHttpClient jsonHttpClient = new JSONHttpClient();
userAddress = jsonHttpClient.Get(ServiceUrl.UserAddress, nameValuePairs, UserAddress.class);
String id = userAddress.GetId();
}
catch (Exception ex){
String message = ex.getMessage();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute(); //To change body of overridden methods use File | Settings | File Templates.
progressDialog = new ProgressDialog(AccountActivity.this);
progressDialog.setMessage("Loading products. Please wait...");
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtResponsec.setText(userAddress.GetCountry());
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
}
AccountActivity.java
public class AccountActivity extends AppCompatActivity {
Toolbar toolbar;
ActionBar actionBar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Info.","Address","Contact","Email"};
int Numboftabs =4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (toolbar != null) {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_account, 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);
}
}
You should change
progressDialog = new ProgressDialog(AccountActivity.this);
to
progressDialog = new ProgressDialog(getActivity());
in Tab1 Fragment also i see txtResponsec=null you forget to initialized it.
Edit:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
txtResponsec=(TextView)v.findViewById(R.id.txtResponsecId);
return v;
}

Back press feature for navigation drawer not working

I'm trying to implement the back press feature for a fragment and activity regarding the navigation drawer but it's not working. Does anyone know what I'm doing wrong / what is missing and what needs to be done in order to fix this?
activity class
public class BakerlooHDNActivity extends AppCompatActivity {
//save our header or result
private Drawer result = null;
// Declaring Views and Variables
ViewPager pager;
BakerlooHDNViewPagerAdapter adapter;
BakerlooHDNSlidingTabLayout bakerloohdntabs;
int Numboftabs = 2;
private int getFactorColor(int color, float factor) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= factor;
color = Color.HSVToColor(hsv);
return color;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bakerloo_hdn);
final String actionBarColor = "#B36305";
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if(getSupportActionBar()!=null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hdn) + "</font>"));
getSupportActionBar().setSubtitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.zone_3) + "</font>"));
final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getFactorColor(Color.parseColor(actionBarColor), 0.8f));
}
// start of navigation drawer
headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withCompactStyle(true)
.withHeaderBackground(R.color.bakerloo)
.withProfileImagesVisible(false)
.withTextColor(Color.parseColor("#FFFFFF"))
.withSelectionListEnabled(false)
.addProfiles(
new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
)
.build();
result = new DrawerBuilder()
.withActivity(getActivity())
.withAccountHeader(headerResult)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
)
.build();
// end of navigation drawer
}
#Override
public void onBackPressed() {
if (result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent("BACKPRESSED_TAG"));
}
}
fragment class
public class FragmentBakerlooHDN extends android.support.v4.app.Fragment {
public FragmentBakerlooHDN() {
// Required empty constructor
}
BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do stuff when back in activity is pressed
result.closeDrawer();
}
};
// Declaring navigation drawer
private AccountHeader headerResult = null;
private Drawer result = null;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
public void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(onNotice, new IntentFilter("BACKPRESSED_TAG"));
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bakerloo_hdn, container, false);
// start of navigation drawer
headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withCompactStyle(true)
.withHeaderBackground(R.color.bakerloo)
.withProfileImagesVisible(false)
.withTextColor(Color.parseColor("#FFFFFF"))
.withSelectionListEnabled(false)
.addProfiles(
new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
)
.build();
result = new DrawerBuilder()
.withActivity(getActivity())
.withAccountHeader(headerResult)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
)
.build();
// end of navigation drawer
super.onCreate(savedInstanceState);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
super.onActivityCreated(savedInstanceState);
}
}
try this:
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
public void onCreate() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)) mDrawerLayout.closeDrawer(mDrawerList);
else super.onBackPressed();
}
EDIT:
You can use LocalBroadcastManager to update fragment when in activity back is pressed:
in fragment add new BroadcastReceiver() Instance:
BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do stuff when back in activity is pressed
// headerResult.closeDrawer();
}
};
and register it with tag in onCreate method:
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice,
new IntentFilter("BACKPRESSED_TAG"));
Then, in Activity OnBackPressed method call broadcast:
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("BACKPRESSED_TAG"));
Do you have a reference inside your code to the interface? Looks like you're calling that interface directly hence the errors. Try renaming that method too. It might be conflicting with the super class's onBackPressed method.
Your problem is that your interface is named exactly as the property you are trying to use.
Rename it and use a instance.
#Override
public void onBackPressed() {
OnBackPressedListener instance = getSettedListener();
if (result.isDrawerOpen()) {
result.closeDrawer();
} else {
return instance.onBackPressed();
}
}
public interface OnBackPressedListener {
boolean onBackPressed();
}
This code would compile if you also implement the method getSettedListener on your code (that could be like the following):
public OnBackPressedListener getSettedListener() {
return new OnBackPressedListener(){
boolean onBackPressed(){
if(shouldConsumeBack)
return consumeBack();
else return false;
};
}
}
But this code could return the Fragment that does implements the method.

Doing an Android Silent Mode App, can't even start Main Activity?

I'm working with the Android Application Development for Dummies book by Donn Felker. Specifically, I'm working with the Silent Mode App.
It should be simple to follow the instructions step by step, but as it turns out I can't even start the main activity without crashing the app. I must've gone over my code a dozen times and I can't still figure out what's wrong and make it work without LogCat firing errors like crazy.
Debug device is a Samsung Galaxy SII w/ Android 4.0.3.
Here's the MainAcitivity class
public class MainActivity extends Activity {
Button m_toggleButton = (Button)findViewById(R.id.toggleButton);
AudioManager m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
boolean m_isPhoneSilent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkMode();
toggleImage();
generateClick();
}
#Override
protected void onResume()
{
super.onResume();
checkMode();
toggleImage();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void checkMode()
{
m_audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch(m_audio.getRingerMode())
{
case AudioManager.RINGER_MODE_NORMAL:
m_isPhoneSilent = false;
break;
case AudioManager.RINGER_MODE_SILENT:
m_isPhoneSilent = true;
break;
}
}
private void generateClick()
{
m_toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (m_isPhoneSilent == true)
{
m_audio.setRingerMode
(AudioManager.RINGER_MODE_NORMAL);
m_isPhoneSilent = false;
}
else
{
m_audio.setRingerMode
(AudioManager.RINGER_MODE_SILENT);
m_isPhoneSilent = true;
}
toggleImage();
}
});
}
private void toggleImage()
{
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
Drawable newAsset;
if (m_isPhoneSilent == true)
{
newAsset = getResources().getDrawable(R.drawable.phone_silent);
}
else
{
newAsset = getResources().getDrawable(R.drawable.phone_on);
}
imageView.setImageDrawable(newAsset);
}
I've tried to debug, but I haven't found the problem. Please help.
public class MainActivity extends Activity {
Button m_toggleButton = (Button)findViewById(R.id.toggleButton); //<<<< here
//....your code
you are trying to find Button before setting layout for Activity so move it after setting setContentView as :
public class MainActivity extends Activity {
Button m_toggleButton ;
AudioManager m_audio;
boolean m_isPhoneSilent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_toggleButton = (Button)findViewById(R.id.toggleButton);
m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
///... your code here
You can't call this
Button m_toggleButton = (Button)findViewById(R.id.toggleButton);
AudioManager m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
before your setContentView change it to this:
Button m_;
AudioManager m_audio;
boolean m_isPhoneSilent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_toggleButton = (Button)findViewById(R.id.toggleButton);
m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
....

Categories