How can I send data from activity to fragment via menu? - android

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");

Related

How can I create a method that can I use to send string data to fragment?

I have created a simple WebView app with one single WebView fragment.
I have a navigation drawer with 5 to 6 website URLs and what I want is when someone clicks on that particular link that will be open in that WebView.
Any link clicked open that in a single webview fragment.
I have created this method in MainActivity.java
public void sendData() {
String[] urls = new String[5];
urls[0] = getString(R.string.facebook_url);
urls[1] = getString(R.string.instagram_url);
urls[2] = getString(R.string.youtube_url);
urls[3] = getString(R.string.telegram_url);
urls[4] = getString(R.string.about_url);
Fragment frag = new WebFragment();
Bundle bundle = new Bundle();
bundle.putString("weburl", urls[0]);
bundle.putString("weburl", urls[1]);
bundle.putString("weburl", urls[2]);
bundle.putString("weburl", urls[3]);
bundle.putString("weburl", urls[4]);
frag.setArguments(bundle);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.webContainer, frag).commit();
}
And this is navigation click
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.fbMenu:
sendData();
break;
case R.id.igMenu:
sendData();
break;
case R.id.ytMenu:
sendData();
break;
case R.id.teleMenu:
sendData();
break;
case R.id.about:
sendData();
break;
}
return false;
}
And this is WebView Fragment
webView = view.findViewById(R.id.webViewFragment);
Bundle bundle = this.getArguments();
String webUrls = bundle.getString("weburl");
webView.loadUrl(webUrls);
I don't know how to create a method with parameters and all.
Please help
The method sendData() sets the same URL in this piece of code. Each time you set the "webUrl" with the putString method, it overrides the previous
bundle.putString("weburl", urls[0]);
bundle.putString("weburl", urls[1]);
bundle.putString("weburl", urls[2]);
bundle.putString("weburl", urls[3]);
bundle.putString("weburl", urls[4]);
So the webview will always open the last of the URLs (urls[4]).
I think this is what you are looking for:
public void sendData(String url) {
...
Bundle bundle = new Bundle();
bundle.putString("weburl", url);
...
}
And change the switch to this:
switch (id) {
case R.id.fbMenu:
sendData(getString(R.string.facebook_url););
break;

how to send data from activity to fragment with bottom navigation

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;

How to pass data from Activity to already created Fragment?

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

getting menu press item and passing it to recycler view to set variable

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.

Why bundle deliver null in this code

I want to deliver result from activity to fragment and I have made this code but it is not working.
I really don't know why this code is not working - actually this code is delivering null. I have no idea what should I write a code more.
This is function which send the result
-Sender activity:
public void ResultTofragment(String a, String b){
Bundle args = new Bundle();
args.putCharSequence("t1", a);
args.putCharSequence("t2", b);
Fragment currentFragment = getFragment(FRAGMENT_ONE);
if (args != null) {
currentFragment.setArguments(args);
}
}
private Fragment getFragment(int idx) {
Fragment newFragment = null;
switch (idx) {
case FRAGMENT_ONE:
newFragment = new ExpenseCashFragment();
break;
case FRAGMENT_TWO:
newFragment = new ExpenseAccountFragment();
break;
case FRAGMENT_THREE:
newFragment = new EarningCashFragment();
break;
case FRAGMENT_FOUR:
newFragment = new EarningAccountFragment();
break;
default:
Log.d(TAG, "Unhandle case");
break;
}
return newFragment;
}
This is the function which get the result on fragment.
-Receiver fragment :
public void getVoiceResult(){
Bundle args = getArguments();
CharSequence voiceResult01 = args.getCharSequence("t1");
CharSequence voiceResult02 = args.getCharSequence("t2");
//
cost.setText(""+voiceResult01);
explanation.setText(""+voiceResult02);
}
Put your bundle value into the fragment using
fragmentObject.setArguments(bundle);

Categories

Resources