Example usage for android.app FragmentManager beginTransaction

List of usage examples for android.app FragmentManager beginTransaction

Introduction

In this page you can find the example usage for android.app FragmentManager beginTransaction.

Prototype

public abstract FragmentTransaction beginTransaction();

Source Link

Document

Start a series of edit operations on the Fragments associated with this FragmentManager.

Usage

From source file:com.example.sans.myapplication.AssignActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_assign);

    final SharedPreferences shares = getSharedPreferences("SHARES", 0);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*  ww w .  j a  va 2  s  . com*/

    //requestWindowFeature(Window.FEATURE_NO_TITLE);

    actionBarTitle = (TextView) toolbar.findViewById(R.id.action_bar_title);

    Intent i = getIntent();

    Bundle bundle = i.getExtras();

    try {
        j = new JSONObject(bundle.getString("data", "ERROR"));

    } catch (JSONException e) {
        Toast.makeText(AssignActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    new Thread(new Runnable() {
        @Override
        public void run() {

            for (int i = 30; i > 0; i--) {

                try {
                    Thread.sleep(1000);
                    final int finalI = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            actionBarTitle.setText("" + finalI + "");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            Handler mainHandler = new Handler(AssignActivity.this.getMainLooper());

            Runnable myRunnable = new Runnable() {

                @Override
                public void run() {
                    final Client client = new Client();

                    RequestParams params = new RequestParams();

                    client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", "ERROR"));

                    client.post("OrderDistributor/rejectOrder", params, new JsonHttpResponseHandler());
                }
            };

            mainHandler.post(myRunnable);

            AssignActivity.this.finish();

        }
    }).start();

    setUpMapIfNeeded();

    //Initializing NavigationView

    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    header = navigationView.inflateHeaderView(R.layout.header);
    JSONObject driver_data = null;
    try {
        driver_data = new JSONObject(shares.getString("DRIVER_DATA", "ERROR"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    TextView driver_name_header = (TextView) header.findViewById(R.id.username);
    TextView car_id_header = (TextView) header.findViewById(R.id.car_id);
    final ImageView pp_header = (ImageView) header.findViewById(R.id.profile_image);

    try {
        car_id_header.setText(driver_data.getString("license"));
        driver_name_header.setText(driver_data.getString("name"));
        Client client = new Client();
        client.get(driver_data.getString("image"),
                new FileAsyncHttpResponseHandler(AssignActivity.this.getApplicationContext()) {
                    @Override
                    public void onFailure(int i, Header[] headers, Throwable throwable, File file) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final File response) {

                        AssignActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap image = BitmapFactory.decodeFile(response.getPath());

                                pp_header.setImageBitmap(image);

                            }
                        });

                    }

                });
    } catch (JSONException e) {
        e.printStackTrace();
    }

    header.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(AssignActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", 0);
            AssignActivity.this.startActivity(i);
            drawerLayout.closeDrawers();
        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state

            nav = true;

            menuItem.setChecked(false);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment fragment;
            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {
            case R.id.timetable:
            case R.id.service:
            case R.id.history:
            case R.id.mission:
            case R.id.points:
            case R.id.notice:
                Intent i = new Intent(AssignActivity.this, MenuItemActivity.class);
                i.putExtra("MENU_ITEM", menuItem.getItemId());
                AssignActivity.this.startActivity(i);
                break;
            case R.id.login:
                Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = shares.edit();

                final Client client = new Client();
                RequestParams params = new RequestParams();
                params.put("id", shares.getInt("ID", 0));
                params.put("status", 999);
                client.post("driver/setStatus", params, new JsonHttpResponseHandler());

                editor.putBoolean("ONLINE", false);
                editor.putBoolean("LOGIN", false);
                editor.commit();
                Intent intent = getApplicationContext().getPackageManager()
                        .getLaunchIntentForPackage(getApplicationContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                break;

            }
            return false;
        }
    });

    reject = (Button) findViewById(R.id.reject);

    reject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Client client = new Client();

            RequestParams params = new RequestParams();

            client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", "ERROR"));

            client.post("OrderDistributor/rejectOrder", params, new JsonHttpResponseHandler());

            AssignActivity.this.finish();
        }
    });

    accept = (Button) findViewById(R.id.accept);

    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Client client = new Client();

            final RequestParams params = new RequestParams();

            try {
                params.put("orderId", j.getJSONObject("order_data").getDouble("id"));

                client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", "ERROR"));

                client.post("OrderDistributor/takeOrder", params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable error,
                            JSONObject response) {
                        Log.i("Status Code", "" + statusCode);
                    }
                });

                AssignActivity.this.finish();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
            drawerLayout.setSelected(false);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //calling sync state is necessay or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();
}

From source file:com.example.sans.myapplication.Utility.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    shares = getSharedPreferences("SHARES", 0);

    Client client = new Client();

    loc_array = "";

    RequestParams params = new RequestParams();
    params.put("id", shares.getInt("ID", -1));
    params.put("loc_array", loc_array);

    client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", ""));

    client.post("driver/updateLocation", params, new JsonHttpResponseHandler());

    Fragment newFragment = new OrderListFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.frame, newFragment);
    transaction.addToBackStack(null);/*from   ww  w .jav  a  2 s  .co  m*/
    transaction.commit();

    LocationRequest lr = LocationRequest.create();
    lr.setInterval(1000);
    lr.setFastestInterval(500);
    lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    stored_locations = new ArrayList<Location>();

    controller = (AppController) getApplication();

    controller.startGetStatus();
    controller.startAquireOrder();

    // Initializing Toolbar and setting it as the actionbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    order_num = (TextView) toolbar.findViewById(R.id.order_num);

    order_num.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nav = true;
            Intent i = new Intent(MainActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", R.id.timetable);
            MainActivity.this.startActivity(i);
        }
    });

    toolbar.findViewById(R.id.toolbar_calendar).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nav = true;
            Intent i = new Intent(MainActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", R.id.timetable);
            MainActivity.this.startActivity(i);
        }
    });
    setSupportActionBar(toolbar);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    //Location
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    ll = new myLocationListener();

    startLocationUpdates();

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu

    header = navigationView.inflateHeaderView(R.layout.header);
    JSONObject driver_data = null;
    try {
        driver_data = new JSONObject(shares.getString("DRIVER_DATA", "ERROR"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    TextView driver_name_header = (TextView) header.findViewById(R.id.username);
    TextView car_id_header = (TextView) header.findViewById(R.id.car_id);
    final ImageView pp_header = (ImageView) header.findViewById(R.id.profile_image);

    try {
        car_id_header.setText(driver_data.getString("license"));
        driver_name_header.setText(driver_data.getString("name"));
        client = new Client();
        client.get(driver_data.getString("image"),
                new FileAsyncHttpResponseHandler(MainActivity.this.getApplicationContext()) {
                    @Override
                    public void onFailure(int i, Header[] headers, Throwable throwable, File file) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final File response) {

                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap image = BitmapFactory.decodeFile(response.getPath());

                                pp_header.setImageBitmap(image);

                            }
                        });

                    }

                });
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        SharedPreferences.Editor editor = shares.edit();

        final Client client1 = new Client();
        RequestParams params1 = new RequestParams();

        editor.putBoolean("ONLINE", false);
        editor.putBoolean("LOGIN", false);
        editor.commit();
        Intent intent = getApplicationContext().getPackageManager()
                .getLaunchIntentForPackage(getApplicationContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    header.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(MainActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", 0);
            MainActivity.this.startActivity(i);
            drawerLayout.closeDrawers();
        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state

            nav = true;

            menuItem.setChecked(false);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment fragment;
            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {
            case R.id.timetable:
            case R.id.service:
            case R.id.history:
            case R.id.mission:
            case R.id.points:
            case R.id.notice:
                Intent i = new Intent(MainActivity.this, MenuItemActivity.class);
                i.putExtra("MENU_ITEM", menuItem.getItemId());
                MainActivity.this.startActivity(i);
                break;
            case R.id.login:
                Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = shares.edit();

                final Client client = new Client();
                RequestParams params = new RequestParams();
                params.put("id", shares.getInt("ID", 0));
                params.put("status", 999);
                client.post("driver/setStatus", params, new JsonHttpResponseHandler());

                editor.putBoolean("ONLINE", false);
                editor.putBoolean("LOGIN", false);
                editor.commit();
                Intent intent = getApplicationContext().getPackageManager()
                        .getLaunchIntentForPackage(getApplicationContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                break;

            }
            return false;
        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
            drawerLayout.setSelected(false);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //calling sync state is necessay or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();

}

From source file:com.ithinkbest.taipeiok.NavigationDrawerActivity.java

private void selectItem(int position) {
    // update the main content by replacing fragments
    Fragment fragment = TaipeiFragment.newInstance(position);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.commit();/*www  .ja  v a  2  s.  c  o m*/

    // update selected item title, then close the drawer
    setTitle(mPlanetTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

From source file:com.android.mail.ui.TwoPaneController.java

@Override
public void launchFragment(final Fragment fragment, final int selectPosition) {
    final int containerViewId = TwoPaneLayout.MISCELLANEOUS_VIEW_ID;

    final FragmentManager fragmentManager = mActivity.getFragmentManager();
    if (fragmentManager.findFragmentByTag(TAG_CUSTOM_FRAGMENT) == null) {
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(containerViewId, fragment, TAG_CUSTOM_FRAGMENT);
        mMiscellaneousViewTransactionId = fragmentTransaction.commitAllowingStateLoss();
        fragmentManager.executePendingTransactions();
    }//  w  w w.  j  av  a 2 s .  co  m

    if (selectPosition >= 0) {
        getConversationListFragment().setRawSelected(selectPosition, true);
    }
}

From source file:com.blue.leaves.util.task.SugarTask.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void unregisterHookToContext(@NonNull Fragment fragment) {
    FragmentManager manager = fragment.getChildFragmentManager();

    HookFragment hookFragment = (HookFragment) manager.findFragmentByTag(TAG_HOOK);
    if (hookFragment != null) {
        hookFragment.postEnable = false;
        manager.beginTransaction().remove(hookFragment).commitAllowingStateLoss();
    }/* w  w  w. j a  va 2s  . c  om*/
}

From source file:iovi.testtask.MainActivity.java

private void selectItem(int position) {

    Fragment fragment = new ListF();
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    Bundle args = new Bundle();
    args.putString("Title", mMenuTitles[position]);

    switch (position) {
    case 0:// w w  w  . j  a  va  2s . c om
        args.putString(ListF.TABLE, DataBaseHelper.TABLE_ORGANISATIONS);
        args.putString(ListF.COLUMN, DataBaseHelper.NAME);
        args.putString(ListF.SELECTION, null);
        args.putStringArray(ListF.ARGS, null);
        fragment.setArguments(args);
        fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        break;
    case 1:
        args.putString(ListF.TABLE, DataBaseHelper.TABLE_NEWS);
        args.putString(ListF.COLUMN, DataBaseHelper.NEWS_TITLE);
        args.putString(ListF.SELECTION, null);
        args.putStringArray(ListF.ARGS, null);
        fragment.setArguments(args);

        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
        break;

    case 2:
        fragment = new ContactsF();
        fragment.setArguments(args);
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

        break;
    }

    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mMenuTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

From source file:com.blue.leaves.util.task.SugarTask.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void registerHookToContext(@NonNull Fragment fragment) {
    FragmentManager manager = fragment.getChildFragmentManager();

    HookFragment hookFragment = (HookFragment) manager.findFragmentByTag(TAG_HOOK);
    if (hookFragment == null) {
        hookFragment = new HookFragment();
        manager.beginTransaction().add(hookFragment, TAG_HOOK).commitAllowingStateLoss();
    }/*  w  w  w.  j  a  v  a 2  s .  co m*/
}

From source file:at.software2014.trackme.MainActivity.java

public void selectItem(int position, String argument) {

    Fragment fragment = new Fragment();

    mCurrentPosition = position;//from   w w  w.j ava 2s . c o  m

    switch (position) {
    case 0:
        if (mIsGooglePlayServicesAvailable == true) {
            if (argument == "") {
                fragment = GMapFragment.newInstance(position, mName);
            } else {
                fragment = GMapFragment.newInstance(position, mName, argument);
            }
        }
        break;
    case 1:
        fragment = FriendsListFragment.newInstance(position);
        break;
    case 2:
        fragment = ContactsFragment.newInstance(position);
        break;
    case 3:
        fragment = AboutFragment.newInstance(position);
        break;
    case 4:
        exitActivity();
    }

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mMenuTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerLinear);
}

From source file:com.google.android.gms.example.bannerexample.CreateFile.java

/**
 * Diplaying fragment view for selected nav drawer list item
 * *//*from  w  ww.  j  a  v a  2  s . co m*/
private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
        //fragment = new SearchScreen();
        break;

    case 4:
        //fragment = new BookmarkScreen();
        break;

    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        //  setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

From source file:com.esri.android.mapsapp.MapsAppActivity.java

/**
 * Opens the content browser that shows the user's maps.
 *///from  www . java  2s.c o  m
private void showContentBrowser() {
    FragmentManager fragmentManager = getFragmentManager();
    Fragment browseFragment = fragmentManager.findFragmentByTag(ContentBrowserFragment.TAG);
    if (browseFragment == null) {
        browseFragment = new ContentBrowserFragment();
    }

    if (!browseFragment.isVisible()) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.maps_app_activity_content_frame, browseFragment, ContentBrowserFragment.TAG);
        transaction.addToBackStack(null);
        transaction.commit();

        invalidateOptionsMenu(); // reload the options menu
    }

    mDrawerLayout.closeDrawers();
}