How to get Bundle state in my activity for menu item - android

I have an application android where to start step one bundle.putString ("statusLogin", "unlogged"); referring to my state of login, and so some features hidden buttons.
In my menu item an option "login as admin" that after the login has been carried out step a new parameter for the bundle: bundle.putString ("statusLogin", "Logged") and so I set visible the buttons allowed only to administrator .
Until then fine, but that in menu item possess the button "Init" where I would need to seek the status of Bundle without creating a new one so i can verify that it is logged in or not and show buttons allowed.
This is my main activity
public class PrincipalActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
FragmentManager fragmentManager = getSupportFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("statusLogin", "Unlogged");
TelaInicialFragment fragobj = new TelaInicialFragment();
fragobj.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.principal, fragobj).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_principal, menu);
return super.onCreateOptionsMenu(menu);
}
public static PrincipalActivity newInstance(Context context) {
PrincipalActivity principalActivity = new PrincipalActivity();
return principalActivity;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
int itemId = item.getItemId();
switch (itemId) {
case R.id.init:
Bundle bundle = new Bundle();
bundle.putString("statusLogin", "Unlogged");
TelaInicialFragment fragobj = new TelaInicialFragment();
fragobj.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.principal, fragobj).commit();
break;
case R.id.sincronizar:
break;
case R.id.logarAdmin:
fragmentManager.beginTransaction().replace(R.id.principal, new LoginFragment()).commit();
break;
case R.id.sair:
finish();
break;
default:
return false;
}
return true;
}
}
How can I check the Bundle state to ensure that the user is currently authenticated?

Related

Action Bar Items are clickable, but do not respond to events in a Fragment

Basically my project have to have different toolbars, one for each fragment switched by the bottom navigation bar.
The fragment toolbars items are clickable, when I long press, shows the title item etc, but they don't perform the action. For example, When I set to show a toast when click on that item, he'll not perform. Any Suggestion? Thanks.
public class FeedFragment extends Fragment {
public static final String TAG = "Tag Free";
DialogFragment mDialog;
FloatingActionButton fab;
RevealFrameLayout reveal;
FrameLayout frame;
private ConstraintLayout layoutDialog;
boolean isOpen = false;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
/** Toolbar **/
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(false);
// navigation bottom
fab = getActivity().findViewById(R.id.fab_button);
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pencil_black_24dp));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction().setCustomAnimations(R.anim.hold, R.anim.slide_down);
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = new PostDialog();
dialogFragment.show(ft, "dialog");
dialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragmentTheme);
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
return true;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
You are not chaining to the superclass in the activity methods.
Refactor your code as below :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
break;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
break;
}
return super.onOptionsItemSelected(item);
}
Hope now your code will work fine.

replace action bar up button with navigation slider when it is clicked

I have implemented a navigation slider in my app. In this slider I have four fragments: Home, Profile, Search, calculator. Don't worry about the naming conventions in selectItem method as I am only focusing on searchProgram as of now and don't have all my four fragments implemented
NavigationDrawer.class (Activity):
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomePage();
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new SearchProgram();
default:
break;
}
if (fragment != null) {
Bundle bundle = new Bundle();
bundle.putInt(HomeFragment.EXTRA_ITEM_INDEX, position);
bundle.putString("username", userName);
bundle.putString("access_token", access_token);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavItems[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
When I select search i am brought to a view which has an action bar with the navigation slider just like I wanted. When the user selects what they want to search for from the two spinners and clicks my own button called search I then start a master detail flow containing an expandable list.
Below is where i start my new activity from my searchProgram class(Fragment):
protected void onPostExecute(ArrayList<SportProgram> programList) {
Bundle extras = new Bundle();
String userName = getArguments().getString("username");
String access_Token = getArguments().getString("accessToken");
System.out.println("Search Program Test Username: " + userName);
System.out.println("Search Program Test Access_Token: " + access_Token);
extras.putString("username", userName);
extras.putString("accessToken", access_Token);
extras.putParcelableArrayList("programs", programList);
Intent intent = new Intent(getActivity(), TrainingProgramListActivity.class);
intent.putExtras(extras);
startActivity(intent);
}
}
This view has an action bar with a back/up button and no navigation slider. When I click this button I am brought back to the previous view, i.e. the search view, however the action bar stays the same and still has the up button. Has anyone any idea on how to change the action bar to include the navigation slider like it did previously? also when I select the back/up button in my listActivity view I am replacing the current fragment as follows:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list_program, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (item.getItemId()) {
//This is the back/up button
case android.R.id.home:
fragment = new SearchProgram();
break;
case R.id.action_home:
Intent homeIntent = new Intent(this, NavigationDrawer.class);
Bundle extras = this.getIntent().getExtras();
homeIntent.putExtras(extras);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
System.out.println("HIT HOMEINTENT");
return true;
case R.id.action_search:
fragment = new SearchProgram();
System.out.println("HIT SEARCH");
break;
default:
break;
}
if (fragment != null) {
Bundle bundle = this.getIntent().getExtras();//new Bundle();
// bundle.putString("username", userName);
// bundle.putString("access_token", access_token);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.containerE, fragment).commit();
// fragment.getActivity().supportInvalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
I have tried numerous possible solutions but keep falling short. All the examples i have found navigate from the navigationDrawer activity to a fragment and then another fragment but for me I am navigating from NavigationDrawer to a fragment->class->fragment. Any ideas please?
You are stacking a detail activity on top of the main one which holds your drawer. To get back to the original activity, just close the last one using finish(), in your onOptionsItemSelected().

Replacing Fragment does not change properly

The issue occurs when I attempt to switch from the Second Fragment to the First Fragment. I am using ActionBar Option Menu Icons to navigate back and forth between the different fragments.
Each fragment has its own menu that is associated with the individual option menu items. I cannot seem to figure out why I am able to transition from one the First Fragment to the Second Fragment, but am unable to do the reverse.
Does anything in my code stand out that would disable me from being able to navigate back to the previous fragment?
I was able to switch between the fragments without any issues in the past, but after I incorporated these option menu items to do the navigation, it stopped working.
Starting Fragment
public class SearchFragmentActivity extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_search_fragment,
container, false);
btnBasketball = (ImageButton) view.findViewById(R.id.btnBasketball);
btnBasketball.setOnClickListener(this);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
menu.clear();
inflater.inflate(R.menu.navigation_search_event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_more:
// do something with a dropdown
break;
}
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnBasketball:
changeFragment("Basketball");
break;
}
}
public void changeFragment(String sportName) {
Bundle bundle = new Bundle();
bundle.putString("SPORTNAME", sportName);
Fragment fragment = new SearchDetailsFragmentActivity();
fragment.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchFragment, fragment);
transaction.commit();
}
}
Second Fragment
public class SearchDetailsFragmentActivity extends Fragment {
TextView tvSportsName;
GridView gView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_search_details_fragment,
container, false);
String sportsName = getArguments().getString("SPORTNAME");
tvSportsName = (TextView) view.findViewById(R.id.tvSportsName);
tvSportsName.setText(sportsName);
// SportAdapter sAdapter = new SportAdapter(getActivity(), lstSports);
gView = (GridView) view.findViewById(R.id.gridViewSearch);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
menu.clear();
inflater.inflate(R.menu.navigation_search_details_event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_cancel:
changeFragment();
break;
}
return true;
}
public void changeFragment() {
Fragment fragment = new SearchFragmentActivity();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.commit();
}
}
Options Menu associated with Second Fragment
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/action_cancel"
android:icon="#drawable/ic_content_remove"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="always"/>
</menu>
UPDATES
These changes allow me to navigate backwards from the SearchDetailsFragmentActivity >> SearchFragmentActivity using the SoftKey Back Button.
Changes to the changeFragment() method inside SearchDetailsFragmentActivity
public void changeFragment() {
Fragment fragment = new SearchFragmentActivity();
FragmentManager fm = getFragmentManager();
//FragmentTransaction transaction = fm.beginTransaction();
//transaction.setCustomAnimations(R.anim.cell_left_in,
//R.anim.cell_right_out);
//transaction.replace(R.id.searchDetailsFragment, fragment);
//transaction.commit();
fm.popBackStack();
}
inside the SearchFragmentActivity
public void changeFragment(String sportName) {
Bundle bundle = new Bundle();
bundle.putString("SPORTNAME", sportName);
Fragment fragment = new SearchDetailsFragmentActivity();
fragment.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.setCustomAnimations(R.anim.cell_left_in,
R.anim.cell_right_out);
transaction.replace(R.id.searchFragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
UPDATE 2
I placed a Log.e inside the OnOptionItemSelected() to see if the button was even firing properly and it appears as if it is not. There is nothing that is getting logged.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_cancel:
Log.e("IS THIS WORKING", "THIS IS WORKING"); <<< NOT FIRING
changeFragment();
break;
}
return true;
}
When replacing a fragment, you need to indicate whether or not that transaction is reversable (i.e. whether or not it goes onto the backstack). For the first fragment transaction, you usually won't want to do this (wouldn't want to pop to an empty view). For fragment replacements, you want to specify addToBackStack() with an optional tag (which can be later used with popBackStack(String)).
For example, in between these lines:
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.commit();
add:
transaction.replace(R.id.searchDetailsFragment, fragment);
transaction.addToBackStack(null);
transaction.commit();

How to send data from main activity to fragment

public class MyActivity extends Activity implements ButtonFragement.OnFragmentInteractionListener, TextFragment.OnFragmentInteractionListener,Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ButtonFragement btnfrg=new ButtonFragement();
TextFragment txtfrg= new TextFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.my_activity,btnfrg,"Fragment");
ft.add(R.id.my_activity,txtfrg,"Second Fragment");
ft.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void respond(String data) {
FragmentManager fm=getFragmentManager();
TextFragment f1= (TextFragment) fm.findFragmentById(R.id.textfrg);
f1.changeText(data);
}
}
This is my main_Activity code, here i am trying to send a data over the fragment but it gives me error at f1.changeText(data).Basic structure of my project is , on main Activity , i created two fragment. One with button and another with text. I want to show how many times the button was clicked on second fragment using a communicator interface. Here in "data" counter shows a how many times button was clicked but i am not able to transfer it over second fragment.
Complete Code for the Program---
public interface Communicator {
public void respond(String data);
}
In TextFragment class i added this method----
public void changeText(String data)
{
txt.setText(data);
}
In ButtonFragment class i added and modified following method
public class ButtonFragement extends Fragment implements View.OnClickListener{
int counter=0;
private OnFragmentInteractionListener mListener;
Button btn;
Communicator comm;
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
comm= (Communicator) getActivity();
btn= (Button) getActivity().findViewById(R.id.button);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
counter++;
// comm.respond("The button was clicked "+counter+" times");
comm.respond("hi");
}
Here, i just added which i added in my program. My program get crash at...MainActiviy f1.changeText(data);
But why i am not getting it.Can anyone Help me fixed this bug?
Bundle bundle = new Bundle();
bundle.putString("key", value);
// set Fragmentclass Arguments
YourFragment ff= new YourFragment ();
ff.setArguments(bundle);
transaction.add(R.id.my_activity, ff);
Using Bundle
From Activity:
Bundle bundle = new Bundle();
bundle.putString("message", "Hello!");
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
String myValue = this.getArguments().getString("message");
...
...
}
You have no fragment with id R.id.textfrg.
You are for some reason adding two fragments with id R.id.my_activity. One with tag "Fragment" and another with tag "Second Fragment".
So you are getting error.
Your idea is rigth.
This may be helpfull
TextFragment f1= (TextFragment) fm.findFragmentByTag("Second Fragment");
DO this way:
On Activity Side.
Fragment fragment = new GridTemplate();
Bundle bundle = new Bundle();
bundle.putInt("index",your value);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
here R.id.frame_container is a frame Layout or Relative Layout In which you have to add the fragment.
On Fragment Side.
int index = getArguments().getInt("index");
hope this wil solve your problem. Thanks

Start ListPreference (fragment) from MenuItem

I'm trying to start up a preference fragment from a MenuItem and I'm having some trouble. I followed a tutorial on how to make a listPreference and then adapted it to my project, but it crashes the app.
This is the item in which is the launch point for the intenet to the prefFrag:
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/settings"
android:onClick="prefStartup"/>
Here is the code that launches the intent in the main activity:
public void prefStartup(MenuItem item){
Intent intentSetPref = new Intent(getApplicationContext(), PrefActivity.class);
startActivityForResult(intentSetPref, 0);
}
Here are the two classes that help display the fragment (straight from the tutorial):
public class PrefActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PrefFragment prefFragment = new PrefFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, prefFragment);
fragmentTransaction.commit();
}
}
public class PrefFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
I'm not really sure why it would be breaking if the stuff is straight from the tutorial. In the tutorial though they just launch it from a regular button rather than a MenuItem.
I followed the same tutorial as you not long ago and managed to stumble my way through the same problem.
Instead of using your prefStartup() try the following in your main activity.
//Method for creating options menu
#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;
}
//Method for handling options menu selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_settings was selected
case R.id.action_settings:
Intent intentSetPref = new Intent(getApplicationContext(), PrefActivity.class);
startActivityForResult(intentSetPref, 0);
break;
default:
break;
}
return true;
}
You can remove the android:onClick="prefStartup" from your menu xml as well.

Categories

Resources