How to open fragment class through intent in another activity? - android

My SlidingScreenActivity code is,
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
public void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 1:
fragment=new HomeFragment();
break;
case 2:
fragment=new Mywallet();
break;
case 3:
fragment=new AboutUsFragment();
break;
default:
break;
}
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.closeDrawer(mDrawerList);
Log.e("SlidingMainActivity", "Error in creating fragment");
}
}
Another Activity button listener,
btnWallet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mIntent=new Intent(this,SlidingScreenActivity.class);
startActivity(mIntent);
}
});
How can i openMyWallet fragment that i have already declared in case 2: in SlidingScreenActivity.class ,when click on button in another activity through Intent?
could anyone help me?
Thanks in advance...

SlidingScreenActivity:
#Override
protected void onStart() {
super.onStart();
displayView(getIntent().getIntExtra("position", 2));
}
Another Activity button listener:
btnWallet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mIntent=new Intent(this,SlidingScreenActivity.class);
intent.putExtra("position", 2);
startActivity(mIntent);
}
});

Related

How to call Android Activity on Click of Slider Menu Item

i want call simple Android Activity On click of Slider Menu Item, on place of fragment.
i tried to called activity using fragment but it shows nothing
please help me.
can anyone suggest alternate way rather than this ?
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
Log.e("", "In Fragment "+position);
fragment = new About_us_Activity();
//startActivity(new Intent(this,Home_Activity.class));
break;
case 1:
//fragment = new About_us_frag();
Log.e("", "In Fragment "+position);
break;
case 2:
Log.e("", "In Fragment "+position);
fragment = new About_us_frag1();
break;
default:
break;
}
if (fragment != null) {
Log.e("", "In Fragment");
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
First of all apply onItemClickListener to your drawer list.
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawers();
displayView(position);
}
});
In your DisplayView method:
private void displayView(int position) {
switch (position) {
case 1:
Intent intent = new Intent(getApplicationContext(), MyActivity1.class);
startActivity(intent);
break;
case 2:
Intent intent1 = new Intent(getApplicationContext(),MyActivity2.class);
startActivity(intent1);
break;
default:break;
}
}
MyActivity1 and MyActivity2 are activities. you can try this method , it worked for me.

Getting Empty fragment after popbackstack

When I am pressing back button getting the fragment as empty. Not getting the previous fragment poped back. Tried many solutions but didn't work. What is the solution for this ? I have no idea how to solve this.
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = mHomeFragmentInstance;
break;
case 1:
fragment = mOrderFragmentInstance;
break;
case 2:
fragment = mOrdersheetFragmentInstance;
break;
case 3:
fragment = mMyorderwidgetFragmentInstance;
break;
case 4:
Intent intent=new Intent(this,LoginActivity.class);
startActivity(intent);
clearValues();
finish();
return;
default:
fragment = mHomeFragmentInstance;
break;
}
if (fragment != null) {
replaceFragment(fragment, position);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void replaceFragment(Fragment fragment){
if (fragment != null) {
Fragment currentFragment = this.getSupportFragmentManager().findFragmentById(R.id.frame_container);
if(null != currentFragment ){
if(currentFragment.equals(fragment)){
return;
}else{
getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
}
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
public void replaceFragment(Fragment fragment, int position){
adapter.selectItem(position);
Log.i("TAG", "replaceFragment:"+fragment.getClass().getName()+":"+position);
replaceFragment(fragment);
Log.i("TAG", "Add"+fragment.getClass().getName()+"backStackFragment");
if(fragment.equals(mHomeFragmentInstance)){
Log.i("TAG", "clear backStackFragment");
backStackFragment.clear();
backStackFragment.add(mHomeFragmentInstance);
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(drawerContainer);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getActionBar().setTitle(Html.fromHtml("<font color='#983A1B'>" + title + "</font>"));
View view = getActionBar().getCustomView();
//((TextView)view.findViewById(R.id.title)).setText(Html.fromHtml("<font color='#983A1B'>" + title + "</font>"));
((TextView)view.findViewById(R.id.title)).setText(Html.fromHtml("<font color='"+ ApplicationInfo.getPlfColor(this)+"'>" + title + "</font>"));
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if(fm.getBackStackEntryCount() > 1) {
fm.popBackStack();
}else {
//super.onBackPressed();
finish();
}
}
}
Just add addToBackStack while you are transitioning between your fragments like below:
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();
if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.

null pointer when try to add fragment inside another fragment

I have the following structure
Activity
|________ Spinner
|________ TabHost
|_______ Fragment1
|________ LinearLayout
|_______ Fragment2
when I change the option in spinner i should add (Fragment3 OR Fragment4 OR Fragment5) inside LinearLayout
the code that I am using in the spinner
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Fragment1 fragment = (BaseFragment) mTabFragments.get(mTabHost.getCurrentTab());
fragment.updateCurrentFragment(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
The code of adding the fragment
public void updateCurrentFragment (int index) {
switch (index) {
case 0:
replaceFragment(new Fragment3());
break;
case 1:
replaceFragment(new Fragment4());
break;
case 2:
replaceFragment(new Fragment5());
break;
}
}
public void replaceFragment (Fragment newFragement) {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_layout, newFragement);
transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
transaction.commit();
}
I am now getting null pointer exception, and getActivity = null
Though you haven't share the entire class, seems updateCurrentFragment() and replaceFragment() functions has been written within the Interface BaseFragment or within the individual Fragment1, Fragment2 etc clases, please correct me if I am wrong. On that case getActivity() will always return null as the new Fragment is yet to be added within the current activity. So may be you need to pass though the instance of the current activity (parent activity) to the BaseFragment or Individual claees extends BaseFragment and then use that instance for getActivity like
(instance of BaseFragment).getActivity() rather than only getActivity().
Here is your modified version of code
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Fragment1 fragment = (BaseFragment) mTabFragments.get(mTabHost.getCurrentTab());
fragment.updateCurrentFragment(**this**,position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public void updateCurrentFragment (ParentActivity pAct,int index) {
switch (index) {
case 0:
replaceFragment(**pAct**,new Fragment3());
break;
case 1:
replaceFragment(**pAct**,new Fragment4());
break;
case 2:
replaceFragment(**pAct**,new Fragment5());
break;
}
}
public void replaceFragment ((ParentActivity pAct,Fragment newFragement) {
FragmentTransaction transaction = **pAct**.getActivity().getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_layout, newFragement);
transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
transaction.commit();
}
Let me know if this solves your problem.

how to create smooth navigation drawer

I am using this example for navigation drawer. When clicking on of item of left drawer listview it shows some images but drawerLayout closes not smoothly.
What should I do here for smoothly close left drawer layout after clicking of the item of listview.
Not sure this is the best route, but the way I solved this was to create a pending Runnable that runs in onDrawerClosed. Eg:
private void selectItem(final int position) {
mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
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(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
mPendingRunnable = null;
}
}
Works perfect
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
mDrawerLayout.postDelayed(new Runnable() {
#Override
public void run() {
selectItem(position);
}
}, 300);
}
}
Just posting the drawerLayout.closeDrawer() on the message queue using the handler, with a minimal delay solved my problem. Handler.postDelayed() is the key here.
public void selectItem(int position)
{
switch (position)
{
case 0:
DashboardFragment dashboardFragment = new DashboardFragment();
Bundle args = new Bundle();
args.putInt(dashboardFragment.ARG_SCREEN_NUMBER, position);
dashboardFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragmentLayout, dashboardFragment, TAG_DASHBOARD);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
break;
default:
break;
}
// Highlight the selected item, update the title, and close the drawer
drawerList.setItemChecked(position, true);
setTitle(mScreenTitles[position]);
mPendingRunnable = new Runnable()
{
#Override
public void run()
{
drawerLayout.closeDrawer(GravityCompat.START);
}
};
mHandler.postDelayed(mPendingRunnable,50);
}
I don't use threads, because i need to update UI after close the navigation menu.
Following code works for me.
i am using fragment as member variable of class to update ui
setFragment() function use to assign fragment to fragment variable
In onDrawerClosed() event, i update ui.
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
setFragment(position);
}
});
// for getting fragment
protected void setFragment(int p)
{
fragment = null;
switch (position)
{
case 1:
fragment = new DashboardFragment();
break;
}
if (fragment != null)
{
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(p);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
// on close draw , fragment is loaded on screen
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
Please review my MainActivity to make smooth DrawerLayout (open/close) with a custom topBar layout.
public class MainActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment = null;
Class fragmentClass = null;
FrameLayout frameLayout;
TextView topTilte;
DrawerLayout drawer;
NavigationView navigationView;
private boolean isDrawerOpen = false;
#Override
protected void onCreateFinished() {
setContentView(R.layout.activity_main);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
topTilte = findViewById(R.id.toolbar_title);
fragmentClass = HomeFragment.class;
topTilte.setText(R.string.menu_home);
setFragment();
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View view, float slideOffset) {
if(slideOffset > .55 && !isDrawerOpen){
onDrawerOpened(view);
isDrawerOpen = true;
} else if(slideOffset < .45 && isDrawerOpen) {
onDrawerClosed(view);
isDrawerOpen = false;
}
}
#Override
public void onDrawerOpened(#NonNull View view) {
}
#Override
public void onDrawerClosed(#NonNull View view) {
}
#Override
public void onDrawerStateChanged(int i) {
}
});
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void afterInjection() {
}
public void openMenu(View v) {
drawer.openDrawer(Gravity.LEFT);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
topTilte.setText(R.string.menu_home);
fragmentClass = HomeFragment.class;
setFragment();
} else if (id == R.id.nav_profile) {
}
return true;
}
private void setFragment() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}, 200);
}
}

Closing Sliding menu onItemClick

So, I'm using jfeinstein10 library for my SlidingMenu. It works fine but I'm having a problem to toggle the menu when the user taps in one of the menu options.
I have the MainActivty where the slidingmenu is and a fragment called SampleListFragment where I set the menu options.
What I'm trying to do is call a function from the MainActivity when I click the option. This function should only toggle the menu, but instead I get a NullPointException error.
My MainActivity
public class MainActivity extends BaseActivity implements SlidingActivityBase {
private SlidingMenu menu;
private ImageButton btn_pesquisa;
private ImageButton btn_toggle;
private MakeMateria makeMat = new MakeMateria();
private static final int SCREEN_ORIENTATION_PORTRAIT = 1;
String id_test;
SampleListFragment listFragment = new SampleListFragment();
public MainActivity() {
super(R.string.title_bar_content);
}
public void mainToggle() {
Log.d("1", "" + this);
toggle();
Log.d("2", "" + this);
}
public static Intent newInstance(Activity activity, int pos) {
Intent intent = new Intent(activity, MainActivity.class);
intent.putExtra("pos", pos);
return intent;
}
public void testeEvent(){
Log.d("Funciona","works");
toggle();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
R.drawable.titlebar);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setBackgroundDrawable(bg);
BitmapDrawable bgSplit = (BitmapDrawable) getResources()
.getDrawable(R.drawable.titlebar);
bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
}
int pos = 0;
if (getIntent().getExtras() != null) {
pos = getIntent().getExtras().getInt("pos");
}
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
menu = new SlidingMenu(this);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setBehindScrollScale((float) 1.0);
menu.setMenu(R.layout.menu_frame);
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new MainFragment()).commit();
setSlidingActionBarEnabled(true);
btn_pesquisa = (ImageButton) findViewById(R.id.btnPesquisa);
btn_toggle = (ImageButton) findViewById(R.id.btn_menu);
btn_toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
toggle();
}
});
btn_pesquisa.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SearchActivity.class);
//startActivity(intent);
overridePendingTransition(R.anim.view_transition_in_left,
R.anim.view_transition_out_left);
}
});
}
public void getMenu(){
menu.toggle();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
This part is from my fragment:
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
android.support.v4.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
Log.d("1", "1");
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
mainActivity.getMenu();
break;
case 1:
Log.d("2", "2");
toggle();
break;
case 2:
Log.d("3", "3");
toggle();
break;
case 3:
Log.d("4", "4");
toggle();
break;
case 4:
Log.d("5", "5");
toggle();
break;
case 5:
Log.d("6", "6");
toggle();
break;
case 6:
Log.d("7", "7");
toggle();
break;
case 7:
Log.d("8", "8");
toggle();
break;
case 8:
Log.d("9", "9");
toggle();
break;
}
if (newContent != null)
switchFragment(newContent);
}
MainActivity mainActivity is global, and the insance of it I did in the onCreateView.
The NPE points to the lines where I call the function and where I call the toggle inside the function.
Many thanks.
I did this -> Android : Accessing container activity object from fragment using putExtra?
The problem was that I passing a null object, but when I did like this ->
((MainActivity) this.getActivity()).getMenu()
I was able to get the correct value from the object.
#Wenger thanks for the help.

Categories

Resources