Hi everyone can help me pls
I want send data from activity to fragment but I using bottom navigation
I using Intent to send data from activity 1 to activity 2 (activity 2 have bottom navigation)
I want to send data to Home_Fragment what should I Used ?
BottomNavigationView bottomNav = findViewById(R.id.top_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home_Fragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedItem = null;
switch (menuItem.getItemId()){
case R.id.navigation_home:
selectedItem = new Home_Fragment();
break;
case R.id.navigation_project:
selectedItem = new Project_Fragment();
break;
case R.id.navigation_persons:
selectedItem = new Persons_Fragment();
break;
case R.id.navigation_accounts:
selectedItem = new Accounts_Fragment();
break;
case R.id.navigation_other:
selectedItem = new Others_Fragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedItem).commit();
return true;
}
};
just initialize your fragment from itself and pass any data inside initialize method.
so by example if we want to pass a String value to fragmen we should make it like this inside fragment :
public static YourFrament getInstance(String example) {
YourFrament fragment = new YourFrament();
Bundle bundle = new Bundle();
bundle.putString("key", example);
fragment.setArguments(bundle);
return fragment;
}
and to get data you should receive it from onCreate method inside fragment like this :
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
String value = getArguments().getString("key");
}
so from activity we should call fragment like this :
case R.id.navigation_accounts:
selectedItem = YourFrament.getInstance("string example");
break;
Assuming you want to pass the data when you initialize the fragment, you could try and create a Bundle object, add your data to the bundle.
Then initialize your fragments using a static newInstance(Bundle args) passing in your bundle.
So basically your fragments would look something like this.
public class HomeFragment extends Fragment{
public static Fragment newInstance(Bundle args){
// get your data and do whatever
return new HomeFragment(); }
Then in your onNavigationItemSelected() method
case R.id.navigation_home:
Bundle bundle = new Bundle();
bundle.putInt(AGE, 22); // put whatever data you want to pass to the fragment.
selectedItem = HomeFragment.newInstance(bundle)
break;
Related
So in my android app I am using a menu and fragments, and after the user logs in I want to be able to pass the username for example from the login activity to all my other fragments, I tried few solutions but none of them seemed to work, here's what I've done so far:
In my LoginActivity I am able to pass the username like this:
final Bundle bundle = new Bundle();
bundle.putString("username", username.getText().toString());
And in my MenuActivity this is what I've done to get data from the LoginActivity:
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra("username")) {
username = intent.getStringExtra("username");
}
}
And this to pass the data to my different fragments:
final Bundle bundle = new Bundle();
bundle.putString("username", username);
bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.home:
fragment = new HomeFragment();
fragment.setArguments(bundle);
break;
case R.id.todo:
fragment = new ToDoFragment();
fragment.setArguments(bundle);
break;
case R.id.schedule:
fragment = new ScheduleFragment();
fragment.setArguments(bundle);
break;
case R.id.courses:
fragment = new CoursesFragment();
fragment.setArguments(bundle);
break;
case R.id.profile:
fragment = new ProfileFragment();
fragment.setArguments(bundle);
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment, "usernameTag").commit();
return true;
}
});
And finally in my HomeFragment:
if(getArguments() != null) {
username = getArguments().getString("username");
}
But it doesn't seem to work, I am able to pass data from activity to another activity or another fragment but while using a menu it didn't wanna work, I keep getting NullPointerException whenever I wanna use "username" in any fragment because it's empty. Does anyone know what I'm doing wrong here?
In order to pass values from activity to activity you can use Intents to pass data instead of bundles
intent.putExtra("username","value");
to pass value from activity to Fragment
final Bundle bundle = new Bundle();
bundle.putString("username", username);
bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
...
}
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment, "usernameTag").commit();
return true;
}
});
then in your Fragment onCreateView() class
Bundle bundle = this.getArguments();
String username= bundle.getString("username");
Lately i've been stuck! I have one Activity (not my MainActivity, I mean, it is not where I created this Fragment), and I need to pass some data. I've already tried to pass using Bundle, using getter, but the same issue appears: "Attempt to invoke virtual method {...} on a null object." at the line where I call the Bundle in the Fragment. I am new at this, so I'm sorry if this is a simple question and I didn't understand. Below the relevant parts of my code:
On Activity (not the main activity):
public void save(){
myGoal = spinnerGoals.getSelectedItem().toString();
Bundle bundle = new Bundle();
bundle.putString("goal", myGoal);
GoalFragment goalFragment = new GoalFragment();
goalFragment.setArguments(bundle);
}
On Fragment (where I want to put this 'goal')
private TextView goal;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate( R.layout.fragment_goal, container, false);
goal = view.findViewById(R.id.myGoalText);
Bundle bundle = getArguments();
if (bundle != null) {
final String myGoal = bundle.getString("goal");
goal.setText(myGoal);
}
return view;
}
On MainActivity (where I created the Fragments):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment() )
.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_goal:
selectedFragment = new GoalFragment();
break;
case R.id.nav_info:
selectedFragment = new InfoFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
Please, I've lost much time trying to solve this by myself hahaha. If anyone can help me, i'd appreciate that!
Create a method in Fragment which you want to receive data, then invoke the method in Activity.
Write this code in Activity :
Bundle bundle = new Bundle();
bundle.putString("goal", myGoal);
fragmentObj.sendData(bundle);
write code in Fragment:
public void sendData(Bundle bundle){
String myGoal = bundle.getString("goal");
}
If the Activity(not main activity) was created from your fragment, you could use
startActivityForResult()
method to receive data after the activity is ended, read about it more here
If that is not the case, you need to persist (in storage) the data using Preferences or Room Database
I am working on app and i have issue when i click on menu button favorite list open but i want access that from main activity is that possible like this in image:
if you want to move from list to item details you can pass your data in the adapter for RecyclerView .
#Override
public void onBindViewHolder(ListAdapter.MyViewHolder holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FavoriteActivity.class);
Bundle bundle = new Bundle();
bundle.putString("yourdata", yourdata);
intent.putExtras(bundle);
context.startActivity(intent);
}
});
}
if you use ListView you can try
your_listview.setOnItemClickListener { parent, view, position, id ->
Intent intent = new Intent(context, FavoriteActivity.class);
Bundle bundle = new Bundle();
bundle.putString("yourdata", yourdata);
intent.putExtras(bundle);
context.startActivity(intent);
}
in FavoritActivity you can set this data by :
String data= getIntent().getExtras().getString("yourdata");
i hope i understood right .
Add to your list item model one more variable and use it.
For example:
boolean isFavorite;
When you create constructor all items false, when you click star to list, make your item's flag to true.
this code i use to open favt activity but this is use for same activity with menu button but i want to open favt fragment from main activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
favListFragment = new FavoriteListFragment();
switchContent(favListFragment, FavoriteListFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate());
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteListFragment is added to the back stack.
if (!(fragment instanceof ProductListFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
I have a navigation drawer set up with different categories. I also have a recycler view that gets the post from firestore (already segregrated in categories) and loads and displays them. my issue is that I want it so when the user presses on that menu item it loads the posts from that category in firestore and displays them. I have attempted to use bundles but have not figured out how to successfully get it to load
adapter:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_categories, container, false);
blog_list = new ArrayList<>();
blog_list_view = view.findViewById(R.id.blog_list_view);
// blogRecyclerAdapter = new BlogRecyclerAdapter(blog_list);
blogRecyclerAdapter = new BlogRecyclerAdapter(getContext(),blog_list);
blog_list_view.setLayoutManager(new LinearLayoutManager(getActivity()));
blog_list_view.setAdapter(blogRecyclerAdapter);
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("politics").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges())
if (doc.getType() == DocumentChange.Type.ADDED) {
BlogPost blogPost = doc.getDocument().toObject(BlogPost.class);
blog_list.add(blogPost);
blogRecyclerAdapter.notifyDataSetChanged();
}
}
});
return view;
}
}
you can see here where it says "politics" is where i need to get the proper menu item to load
navigation drawer:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
break;
case R.id.nav_profile:
Intent profileIntent = new Intent(MainActivity.this, user_profile.class);
startActivity(profileIntent);
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SettingsFragment()).commit();
break;
case R.id.nav_sign_out:
Toast.makeText(this, "SIGNED OUT TEST", Toast.LENGTH_SHORT).show();
FirebaseAuth.getInstance().signOut();
sendToStart();
break;
case R.id.nav_new_post:
Intent postIntent = new Intent(MainActivity.this, NewPost.class);
startActivity(postIntent);
break;
case R.id.nav_politics:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new CategoriesFragment()).commit();
break;
the adapter works fine i just cant figure out how to pass the data to the adapter to load the specif category based on what menu item was selected
First, inside your onNavigationItemSelected, add the info to your CategoriesFragment via a bundle:
case R.id.nav_politics:
CategoriesFragment fragment = new CategoriesFragment();
Bundle args = new Bundle();
args.putString("collection", "politics");
fragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
break;
Next, inside your fragment's onCreate or onStart (not sure about onCreateView) get the string from the bundle:
Bundle bundle = this.getArguments();
if (bundle != null) {
String collection = bundle.getString("collection", "");
}
You can then use it for your Firestore collection.
A future improvement would be extracting politics to a static variable. Another (if passing different values for collection) would be making a helper function you can just pass the collection value to so multiple nav items can use it without code duplication.
Im having a issue I dont know how to resolve.
I have a fragment with a editText and a button.
The button launches a fragment map like this:
public void onClick(View view) {
//Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
Home activity = (Home) getActivity();
if(activity != null)activity.openMapFragment();
break;
}
and the function openMapFragment():
public void openMapFragment(){
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
How would i do to send the text inserted on editText field as a address to look for on map fragment?
You should use bundle to pass data to a fragment :
public void openMapFragment(String args){
Fragment fragment = new gMapFragment();
Bundle bundle = new Bundle();
bundle.putString("foo", args);
fragment.setArguments(bundle);
replaceFragment(fragment);
}
And to retrieve data :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
String foo = getArguments() != null ? getArguments().getString("foo") : "";
//...
}