Change current tab from fragment in android - android

It has 5 tabs. Each tab is a Fragment. What I am looking for is to switch between the tabs programmatically. Tried with the following, but it doesn't help me.
=========================My Main Activity java=========================
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private FirebaseAuth auth;
public ViewPager mViewPager;
public TabLayout tabLayout;
private final String TAG = "ListActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setText("program");
tabLayout.getTabAt(1).setText("security");
tabLayout.getTabAt(2).setText("devices");
tabLayout.getTabAt(3).setText("network");
tabLayout.getTabAt(4).setText("sections");
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavView_Bar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(3);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_home:
break;
case R.id.ic_message:
Intent intent1 = new Intent(MainActivity.this, ActivityOne.class);
startActivity(intent1);
break;
case R.id.ic_add:
if (auth.getCurrentUser() != null) {
createNewListItem();
}else{
Toast.makeText(getApplicationContext(), "You have to Login to Add a new Service!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.ic_profile:
Intent intent3 = new Intent(MainActivity.this, ActivityThree.class);
startActivity(intent3);
break;
}
return false;
}
});
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment());
adapter.addFragment(new Tab2Fragment());
adapter.addFragment(new Tab3Fragment());
adapter.addFragment(new Tab4Fragment());
adapter.addFragment(new Tab5Fragment());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(4);
}
==================================My Fragment==========================
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<SectionDataModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<SectionDataModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String sectionName = dataList.get(i).getHeaderTitle();
ArrayList singleSectionItems = dataList.get(i).getAllItemsInSection();
itemRowHolder.itemTitle.setText(sectionName);
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recycler_view_list.setHasFixedSize(true);
itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
itemRowHolder.recycler_view_list.setNestedScrollingEnabled(false);
/* itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
itemRowHolder.btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TabLayout tabLayout = (TabLayout)v.findViewById(R.id.tabs);
Toast.makeText(v.getContext(), "click event on more, "+sectionName , Toast.LENGTH_SHORT).show();
if (sectionName=="sections"){
tabLayout.getTabAt(5).select();
}else if (sectionName=="network"){
tabLayout.getTabAt(4).select();
}else if(sectionName=="devices"){
tabLayout.getTabAt(3).select();
}else if(sectionName=="security"){
tabLayout.getTabAt(2).select();
}else {
tabLayout.getTabAt(1).select();
}
}
});

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.
Once it has implemented that interface, you could do anything you want in the method it overrides.
There is a good tutorial on how to do exactly this kind of thing.
I hope this was helpful to you!

1) Make one method in MainActivity
public void setCurrentTab(int position){
viewPager.setCurrentItem(position) //your viewpager object
}
2) Change your onClick listener inside code in MyFragment like below
if (sectionName=="sections"){
((MainActivity)getActivity()).setCurrentTab(4);
}else if (sectionName=="network"){
((MainActivity)getActivity()).setCurrentTab(3);
}else if(sectionName=="devices"){
((MainActivity)getActivity()).setCurrentTab(2);
}else if(sectionName=="security"){
((MainActivity)getActivity()).setCurrentTab(1);
}else {
((MainActivity)getActivity()).setCurrentTab(0);
}

Add this code in your adapter
itemRowHolder.btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sectionName=="sections"){
((MainActivity) mContext).mViewPager.setCurrentItem(5);
}else if (sectionName=="network"){
((MainActivity) mContext).mViewPager.setCurrentItem(4);
}else if(sectionName=="devices"){
((MainActivity) mContext).mViewPager.setCurrentItem(3);
}else if(sectionName=="security"){
((MainActivity) mContext).mViewPager.setCurrentItem(2);
}else {
((MainActivity) mContext).mViewPager.setCurrentItem(1);
}
}
});

Please follow below procedure.
In MainActivity.java
define global constant int n=default_fragment_no
try {
Intent intent = getIntent();
String N = intent.getStringExtra("N");
n = Integer.parseInt(N);
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
viewPager.setCurrentItem(n);
In your fragment
itemRowHolder.btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TabLayout tabLayout = (TabLayout)v.findViewById(R.id.tabs);
Toast.makeText(v.getContext(), "click event on more, "+sectionName , Toast.LENGTH_SHORT).show();
if (sectionName=="sections"){
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("N", "5");
startActivity(intent);
}else if (sectionName=="network"){
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("N", "4");
startActivity(intent);
}else if(sectionName=="devices"){
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("N", "3");
startActivity(intent);
}else if(sectionName=="security"){
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("N", "2");
startActivity(intent);
}else {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("N", "1");
startActivity(intent);
}
}
});

Related

How to open link in a fragment with webview when a specific item is clicked from listview fragment

I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped

Navigation drawer is not updating selected state onBackPressed

I am A Beginner in android development, actually I have a Navigation drawer with Fragments my issue is when i go to fragment b from a the state in navigation drawer is updating to fragment b successfully but when go to fragment B From Fragment A by on 'backpressed' method the drawer item state is not updating / changing to fragment A . please help me in fixing this.
Here is my Main Activity Code :
public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
//, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_PERMISSION = 10;
private Toolbar toolBar;
private NavigationView navDrawer;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private View btnLogOut;
private int selectedItem;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
// private GoogleApiClient googleApiClient;
private FloatingActionButton fab;
private CoordinatorLayout coordinatorLayout;
private HomeFragment homeFragment=new HomeFragment();
final String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String userID = user.getUid();
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
startActivity(intent);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_content, homeFragment);
tx.commit();
final WebView webView = (WebView) findViewById(R.id.WV);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
// do your stuff here}
#Override
public void onReceivedError (WebView view,int errorCode, String description, String
failingUrl){
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("https://google.co.in");
requestAppPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
R.string.msg,REQUEST_PERMISSION);
toolBar =(Toolbar)
findViewById(R.id.app_bar);
setSupportActionBar(toolBar);
// If a notification message is tapped, any data accompanying the notification
// message is available in the intent extras. In this project the launcher
// intent is fired when the notification is tapped, so any accompanying data would
// be handled here. If you want a different intent fired, set the click_action
// field of the notification message to the desired intent. The launcher intent
// is used when no click_action is specified.
//
// Handle possible data accompanying notification message.
if(
getIntent().
getExtras() !=null)
{
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
// subscribeToPushService();
drawerLayout =(DrawerLayout)
findViewById(R.id.drawer_layout);
navDrawer =(NavigationView)
findViewById(R.id.menu_drawer);
navDrawer.setNavigationItemSelectedListener(this);
drawerToggle =new
ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");
}
#Override
public boolean onNavigationItemSelected (MenuItem menuItem){
menuItem.setChecked(true);
selectedItem = menuItem.getItemId();
Fragment fragment = null;
switch (selectedItem) {
case R.id.nav_item_1:
fragment = new HomeFragment();
break;
case R.id.nav_item_2:
fragment = new MicrosoftDskFragment();
break;
case R.id.nav_item_3:
fragment = new GoogleDskFragment();
break;
case R.id.nav_item_4:
fragment = new AppleDskFragment();
break;
case R.id.nav_item_5:
fragment = new OthersDskFragment();
break;
case R.id.nav_item_6:
fragment = new MobiSpecsFragment();
break;
case R.id.nav_item_8:
Intent intent = new Intent(MainActivity.this, About.class);
startActivity(intent);
break;
default:
break;
}
if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
} else {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_content, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
boolean twice = false;
#Override
public void onBackPressed () {
DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
Log.d(TAG, "click");
if (twice == true) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice: " + twice);
//super.onBackPressed();
Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice: " + twice);
}
}, 3000);
}
}
}
#Override
public boolean onKeyDown ( int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
homeFragment.OnKeyDown(keyCode);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#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.profile) {
Intent intent = new Intent(MainActivity.this, Profile.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt("selectedItem", selectedItem);
}
#Override
public void onPermissionsGranted ( int requestCode){
//Do anything when permisson granted
// Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
}
/* #Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
*/
}
}
When you popBackStack() the fragment from back stack will appear on screen so you need to listen for Back stack changes.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
if (fragment != null) {
// check for fragment and set the drawer state
if(fragment instanceof Frag1){
// set drawer state for 1
}else if(fragment instanceof Frag2){
// set drawer state for 2
}
}
}
});

How to add Swipe Down Refresh feature in a Tab View Layout

This is the MainActivity of my Tab View Layout
package com.nitol.aust.cse.austclassmanager;
public class ResultCheckActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private TabLayout t1;
private ViewPager vp1;
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navi_draw_result);
t1 = (TabLayout) findViewById(R.id.tab1);
vp1 = (ViewPager) findViewById(R.id.ViewPager1);
setUpMyViewPager(vp1);
t1.setupWithViewPager(vp1);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout) ;
navigationView = (NavigationView) findViewById(R.id.navigation_view);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle
(this,drawerLayout,toolbar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(5).setChecked(true);
}
void setUpMyViewPager(ViewPager vp){
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addMyFragment(new WebViewEvents(),"News & Events");
viewPagerAdapter.addMyFragment(new WebViewAcademic(),"Academic Calendar");
viewPagerAdapter.addMyFragment(new WebViewTheory(),"Theory Results");
viewPagerAdapter.addMyFragment(new WebViewLab(),"Lab Results");
viewPagerAdapter.addMyFragment(new WebViewTeacher(),"Faculty Members");
vp.setAdapter(viewPagerAdapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> my_list = new ArrayList<Fragment>();
private final List<String> my_title = new ArrayList<String>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
return my_list.get(position);
}
#Override
public int getCount() {
return my_list.size();
}
void addMyFragment(Fragment f, String title){
my_list.add(f);
my_title.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return my_title.get(position);
}
}
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.home:
Intent intent0 = new Intent(ResultCheckActivity.this, MenuActivity.class);
startActivity(intent0);
finish();
break;
case R.id.routine:
Intent intent = new Intent(ResultCheckActivity.this, ClassRoutineActivity.class);
startActivity(intent);
finish();
break;
case R.id.cgpa:
Intent intent2 = new Intent(ResultCheckActivity.this, CgpaCalculator.class);
startActivity(intent2);
finish();
break;
case R.id.details:
Toast.makeText(getApplicationContext(),"Class Details",Toast.LENGTH_SHORT).show();
break;
case R.id.quiz:
Toast.makeText(getApplicationContext(),"Quiz Reminder",Toast.LENGTH_SHORT).show();
break;
case R.id.result:
break;
case R.id.profile:
Intent intent3 = new Intent(ResultCheckActivity.this, ProfileActivity.class);
startActivity(intent3);
finish();
break;
case R.id.about:
Toast.makeText(getApplicationContext(),"About",Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Intent intent4 = new Intent(ResultCheckActivity.this, Settings.class);
startActivity(intent4);
finish();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tool,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.tool_settings){
Intent intent = new Intent(ResultCheckActivity.this, Settings.class);
startActivity(intent);
}
else if(id == R.id.tool_about){
Toast.makeText(getApplicationContext(),"This is About !", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
And this is my those tabs where i want to add refresh feature
void setUpMyViewPager(ViewPager vp){
ViewPagerAdapter viewPagerAdapter = new
ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addMyFragment(new WebViewEvents(),"News & Events");
viewPagerAdapter.addMyFragment(new WebViewAcademic(),"Academic Calendar");
viewPagerAdapter.addMyFragment(new WebViewTheory(),"Theory Results");
viewPagerAdapter.addMyFragment(new WebViewLab(),"Lab Results");
viewPagerAdapter.addMyFragment(new WebViewTeacher(),"Faculty Members");
vp.setAdapter(viewPagerAdapter);
}
Now suppose i want to add refresh on "WebViewEvents" class. The class is given below
package com.nitol.aust.cse.austclassmanager;
public class WebViewEvents extends Fragment {
View v;
WebView wb4;
private String currentUrl = "http://aust.edu/news_events.htm";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.webview_event, container,false);
wb4 = (WebView) v.findViewById(R.id.webView_event);
wb4.setInitialScale(1);
wb4.getSettings().setJavaScriptEnabled(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wb4.setScrollbarFadingEnabled(false);
wb4.loadUrl(currentUrl);
wb4.setWebViewClient(new WebViewClient());
wb4.getSettings().setBuiltInZoomControls(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
return v;
}
}
I found some instructions here but maximum of those was said that i have to #Override onRefresh() method...but i declared my class as a non activity class. so in a non activity class , i can not override a method. that's why i am not finding my solutions...
You just need to read docs on SwipeRefreshLayout
First, add SwipeRefreshLayout to your activity layout:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
// here is your content
</android.support.v4.widget.SwipeRefreshLayout>
Then find instance of swipe refresh layout in your activity:
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
And set refresh listener in which trigger your update method
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
mSwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
myUpdateOperation();
}
}
);
For more information read docs, link in the beginning of the answer.
Also you might look at google samples:
SwipeRefreshLayoutBasic
SwipeRefreshListFragment
List of all google samples you can find here
Hope it helps
Finally this is worked for me
package com.nitol.aust.cse.austclassmanager;
public class WebViewEvents extends Fragment{
View v;
WebView wb4;
SwipeRefreshLayout mySwipeRefreshLayout;
private String currentUrl = "http://aust.edu/news_events.htm";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.webview_event, container,false);
mySwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swiperefresh);
wb4 = (WebView) v.findViewById(R.id.webView_event);
wb4.setInitialScale(1);
wb4.getSettings().setJavaScriptEnabled(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wb4.setScrollbarFadingEnabled(false);
wb4.loadUrl(currentUrl);
wb4.setWebViewClient(new WebViewClient());
wb4.getSettings().setBuiltInZoomControls(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wb4.setWebViewClient(new MyWebViewClient());
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wb4.loadUrl(currentUrl);
}
}
);
return v;
}
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
}
I added this override method inside my class
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wb4.loadUrl(currentUrl);
}
}
);
Then added this to stop the refreshing animation
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
Don't forget to add the instance of the last stopping animation impliment
wb4.setWebViewClient(new MyWebViewClient());

out of memory in MainActivity

Our application android use a lot of memory in MainActivity ( 32MB )
we don't know how to detect and specify where is exactly the problem
we try to comment all the code in MainActivity but No solution
Can someone help us to detect where the solution exactly in our Code ?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> CodeBar = new ArrayList<>();
private ArrayList<Integer> id_Four = new ArrayList<>() ;
private ArrayList<String> nomProd = new ArrayList<>() ;
private ArrayList<String> prix = new ArrayList<>() ;
private ArrayList<String> nomFour = new ArrayList<>() ;
private ArrayList<String> adresse = new ArrayList<>() ;
private ArrayList<String> tel = new ArrayList<>() ;
private ArrayList<String> description = new ArrayList<>() ;
private ArrayList<Float> ratings = new ArrayList<>() ;
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private ShineButton deleteLast;
private final static ArrayList<Integer> resourceIDs = new ArrayList<>();
Intent historiqueIntent;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView title = (TextView) findViewById(R.id.title_promo);
title.setTypeface(title.getTypeface(), Typeface.ITALIC);
deleteLast =(ShineButton)findViewById(R.id.deleteAll);
final MaterialSpinner spinner_search = (MaterialSpinner) findViewById(R.id.spinner);
// final Spinner spinner_search = (Spinner) findViewById(R.id.spinner);
ShineButton btn_search = (ShineButton) findViewById(R.id.searchView);
// spinner_search.setDropdownHeight(1000);
spinner_search.setDropdownMaxHeight(1000);
historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.Ville,android.R.layout.simple_spinner_dropdown_item);
// spinner_search.setAdapter(adapter);
VilleRemember vill = new VilleRemember(getBaseContext() , "" , 0 );
spinner_search.setSelectedIndex(vill.getindiceSelected());
spinner_search.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
#Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
VilleRemember vill = new VilleRemember(getBaseContext() , item,position );
vill.newSelectedVille(position,item);
}
});
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(historiqueIntent);}});
activity=this;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//rotateAnimation(fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lanceScane(activity);
}
});
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
protected void onResume()
{
// System.gc();
super.onResume();
}
//////////////////////////////////////
Timer timer;
int page = 1;
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
// in
// milliseconds
}
// this is an inner class...
class RemindTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (page >= 4) { // In my case the number of pages are 5
// timer.cancel();
page = 0;
// viewPager.setCurrentItem(page--);
// Showing a toast for just testing purpose
/* Toast.makeText(getApplicationContext(), "Timer stoped",
Toast.LENGTH_LONG).show(); */
} else {
viewPager.setCurrentItem(page++);
}
}
});
}
}
#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
int id = item.getItemId();
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.accueil) {
// Handle the camera action
} else if (id == R.id.historique) {
Intent i = new Intent(this , Histourique.class);
startActivity(i);
} else if (id == R.id.prefere) {
Intent i = new Intent(this , Fav_class.class);
startActivity(i);
//overridePendingTransition(R.anim.slide_in_bottom,R.anim.slide_out_bottom);
} else if (id == R.id.parametre) {
Intent i = new Intent(this , Parametres.class);
startActivity(i);
} else if (id == R.id.propose_nous) {
startActivity(new Intent(MainActivity.this, About_us.class));
finish();
} else if (id == R.id.contactez_nous) {
Intent i = new Intent(this , contact_us.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void lanceScane(Activity activity)
{
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scanner");
integrator.setCameraId(0);
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
//historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//historiqueIntent.putExtra("serial",result.getContents());
//startActivity(historiqueIntent);
Intent i = new Intent(MainActivity.this,RechercheResult1.class);
i.putExtra("CodeBar",result.getContents());
Historique his = new Historique(this , result.getContents());
his.insert(result.getContents());
his.remplireDateCode();
startActivity(i);
Toast.makeText(this, "Done! " , Toast.LENGTH_SHORT).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onPause()
{
// System.gc();
super.onPause();
}
//------------------------------------------------------
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
page++;
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
page--;
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
// images dyal les produit proposses :
private void inflateThumbnails() {
System.out.println("==========>"+CodeBar.size());
TextView title = (TextView) findViewById(R.id.title_promo);
if(CodeBar.size() == 0)
{
title.setVisibility(View.INVISIBLE);
deleteLast.setVisibility(View.INVISIBLE);
}
else
{
title.setVisibility(View.VISIBLE);
deleteLast.setVisibility(View.VISIBLE);
}
thumbnailsContainer.removeAllViews();
for (int i = 0; i < CodeBar.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.cardview, null);
TextView price = (TextView) imageLayout.findViewById(R.id.prixprodtestcard);
TextView name = (TextView) imageLayout.findViewById(R.id.nomprodtestcard);
TextView namfou=(TextView) imageLayout.findViewById(R.id.qtestockcard);
TextView rating=(TextView)imageLayout.findViewById(R.id.rating);
ImageView imageProd = (ImageView) imageLayout.findViewById(R.id.imageprodcard);
FloatingActionButton btnlike = (FloatingActionButton) imageLayout.findViewById(R.id.likeButtoncard);
btnlike.setVisibility(View.INVISIBLE);
price.setText(prix.get(i));
name.setText(nomProd.get(i));
namfou.setText(nomFour.get(i));
rating.setText(ratings.get(i).toString());
imageProd.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow View pager to intercept touch events.
System.out.print("=============>ACTION_DOWN");
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
System.out.print("=============>ACTION_UP");
// Allow View pager to intercept touch events.
// v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle Listview touch events.
v.onTouchEvent(event);
return true;
}
});
Glide.with(this)
.load(new TagDatabase().URL_IMAGFOU+"fid="+id_Four.get(i)+"&&code="+CodeBar.get(i)+"&&etat= -99")
.diskCacheStrategy( DiskCacheStrategy.NONE )
.skipMemoryCache( true )
.placeholder(R.drawable.waitloat)
.thumbnail(0.1f)
.into(imageProd);
imageProd.setOnClickListener(onChagePageClickListener(i));
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),InformationsProduit.class);
intent.putExtra("nomProd", nomProd.get(i));
intent.putExtra("prix", prix.get(i));
intent.putExtra("nomFour",nomFour.get(i));
intent.putExtra("etatpromo", -99);//attttt
intent.putExtra("telFour",tel.get(i));
intent.putExtra("addrFour",adresse.get(i));
intent.putExtra("idFour",id_Four.get(i));
intent.putExtra("description",description.get(i));
intent.putExtra("codeBar",CodeBar.get(i));
startActivity(intent);
}
};
}
}

Make back button returns from an activity to a fragment in Android

I'm developing an Android application and I have a fragment called "More", in this fragment I have such things as "About Us", "Terms and Conditions", that are normal activities. What I want to do is, when I click on the back button inside the, for example, the about us Activity I want to return to the "More" fragment. How can I do that? This is what I have in the aboutUs activity:
The "onBackPressed method was supposed to go back to the fragment once I click on the back button, but it is not working. The application crashes and in the log cat is says "Have you declare the MoreFragment Activity in the manifest?", but I tried to declare and it doesn't work.
public class AboutUs extends BaseActivity {
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_us);
image = (ImageView) findViewById(R.id.imageView2);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchactivity = new Intent(AboutUs.this, StartScreenActivity.class);
startActivity(launchactivity);
}
});
}
#Override
public void onBackPressed()
{
Intent intent = new Intent(this,MoreFragment.class);
startActivity(intent);
}
}
This is the fragment that calls the Activity:
public class MoreFragment extends Fragment implements View.OnClickListener {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, null, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView lbl1 = (TextView) view.findViewById(R.id.lbl1);
TextView lbl2 = (TextView) view.findViewById(R.id.lbl2);
TextView lbl3 = (TextView) view.findViewById(R.id.lbl3);
TextView lbl4 = (TextView) view.findViewById(R.id.lbl4);
TextView lbl5 = (TextView) view.findViewById(R.id.lbl5);
TextView lbl6 = (TextView) view.findViewById(R.id.lbl6);
TextView lbl7 = (TextView) view.findViewById(R.id.lbl7);
TextView lbl8 = (TextView) view.findViewById(R.id.lbl8);
TextView lbl9 = (TextView) view.findViewById(R.id.lbl9);
ImageView imv1 = (ImageView) view.findViewById(R.id.imv1);
ImageView imv2 = (ImageView) view.findViewById(R.id.imv2);
ImageView imv3 = (ImageView) view.findViewById(R.id.imv3);
ImageView imv4 = (ImageView) view.findViewById(R.id.imv4);
ImageView imv5 = (ImageView) view.findViewById(R.id.imv5);
ImageView imv6 = (ImageView) view.findViewById(R.id.imv6);
ImageView imv7 = (ImageView) view.findViewById(R.id.imv7);
ImageView imv8 = (ImageView) view.findViewById(R.id.imv8);
ImageView imv9 = (ImageView) view.findViewById(R.id.imv9);
ImageView imv10 = (ImageView) view.findViewById(R.id.imv10);
TextView btnSignOut = (TextView) view.findViewById(R.id.lbl10);
lbl1.setOnClickListener(this);
lbl2.setOnClickListener(this);
lbl3.setOnClickListener(this);
lbl4.setOnClickListener(this);
lbl5.setOnClickListener(this);
lbl6.setOnClickListener(this);
lbl7.setOnClickListener(this);
lbl8.setOnClickListener(this);
lbl9.setOnClickListener(this);
imv1.setOnClickListener(this);
imv2.setOnClickListener(this);
imv3.setOnClickListener(this);
imv4.setOnClickListener(this);
imv5.setOnClickListener(this);
imv6.setOnClickListener(this);
imv7.setOnClickListener(this);
imv8.setOnClickListener(this);
imv9.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
View view9 = view.findViewById(R.id.view9);
View view8 = view.findViewById(R.id.view8);
if (!PrefernceHelper.getBoolean(getActivity(), Commons.Constants.USERLOGGEDIN)) {
imv8.setVisibility(View.INVISIBLE);
lbl8.setVisibility(View.INVISIBLE);
imv10.setVisibility(View.INVISIBLE);
btnSignOut.setVisibility(View.INVISIBLE);
view9.setVisibility(View.INVISIBLE);
view8.setVisibility(View.INVISIBLE);
}
}
private void callAllMoreScreen(String type, Class<?> className) {
Intent intent = new Intent();
intent.setClass(getActivity(), className);
intent.putExtra(Commons.Constants.LOAD_TYPE_URL, type);
getActivity().startActivity(intent);
}
private void callAllMoreScreen1(Class<?> className) {
Intent intent = new Intent();
intent.setClass(getActivity(), className);
getActivity().startActivity(intent);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lbl1:
callAllMoreScreen1(AboutUs.class);
break;
case R.id.lbl2:
callAllMoreScreen("contact-us", AllMoreScreenActivity.class);
break;
case R.id.lbl3:
callAllMoreScreen1(TermsConditions.class);
break;
case R.id.lbl4:
callAllMoreScreen1(PrivacyPolicy.class);
break;
case R.id.lbl5:
callAllMoreScreen("faqs", AllMoreScreenActivity.class);
break;
case R.id.lbl6:
callAllMoreScreen("how-it-work", AllMoreScreenActivity.class);
break;
case R.id.lbl7:
callAllMoreScreen("about-foodlebee", AllMoreScreenActivity.class);
break;
case R.id.lbl8:
callAllMoreScreen(" ", PredefinedAddressActivity.class);
break;
case R.id.lbl9:
callAllMoreScreen(" ", TrackyourorderActivity.class);
break;
case R.id.imv1:
callAllMoreScreen1(AboutUs.class);
break;
case R.id.imv2:
callAllMoreScreen("contact-us", AllMoreScreenActivity.class);
break;
case R.id.imv3:
callAllMoreScreen1(TermsConditions.class);
break;
case R.id.imv4:
callAllMoreScreen1(PrivacyPolicy.class);
break;
case R.id.imv5:
callAllMoreScreen("faqs", AllMoreScreenActivity.class);
break;
case R.id.imv6:
callAllMoreScreen("how-it-work", AllMoreScreenActivity.class);
break;
case R.id.imv7:
callAllMoreScreen("about-foodlebee", AllMoreScreenActivity.class);
break;
case R.id.imv8:
callAllMoreScreen(" ", PredefinedAddressActivity.class);
break;
case R.id.imv9:
callAllMoreScreen(" ", TrackyourorderActivity.class);
break;
case R.id.lbl10:
PrefernceHelper.clearAll(getActivity());
callAllMoreScreen("", SignInActivity.class);
getActivity().finish();
break;
}
}
}
And this is the Activity that call the fragment:
public class TabLayoutScreenActivity extends BaseActivity {
private TabLayout tabLayout;
private Bundle bundle;
//Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); // actionBarSetUp(true);
// getSupportActionBar().setIcon(R.drawable.small_bee);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_launcher);
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
ImageView foodlebee = (ImageView) findViewById(R.id.imageView2);
foodlebee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchactivity = new Intent(TabLayoutScreenActivity.this,StartScreenActivity.class);
startActivity(launchactivity);
}
});
// bundle = getIntent().getExtras();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
if (PrefernceHelper.getBoolean(this, Commons.Constants.USERLOGGEDIN)) {
MenuItem item = menu.findItem(R.id.user_login);
item.setVisible(false);
invalidateOptionsMenu();
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.user_login) {
intentCall(SignInActivity.class, null, 0);
return true;
} else if (item.getItemId() == R.id.home) {
intentCall(StartScreenActivity.class, null, 0);
finish();
return true;
}
return false;
}
#Override
protected void onStart() {
super.onStart();
bundle = getIntent().getExtras();
int tabPostion = 0;
if (bundle != null)
tabPostion = bundle.getInt(Commons.Constants.TAB_POSITION, 0);
TabLayout.Tab tab = tabLayout.getTabAt(tabPostion);
tab.select();
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChefFragment();
case 1:
return new OrderFragment();
case 2:
return new BasketFragment();
case 3:
return new MoreFragment();
default:
return new ChefFragment();
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Chefs";
case 1:
return "Orders";
case 2:
return "Cart";
case 3:
return "More";
default:
return "Chef";
}
}
}
}
Just finish() the current activity in onbackpressed hence you will return to the more fragment because the previous activity is already on the back stack. You don't need to launch the previous activity again.
Moreover your code is wrong.. you are trying to launch a fragment which is not possible. This is why this exception is thrown.
Change your code like this :
#Override
public void onBackPressed()
{
finish();
}

Categories

Resources