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);
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");
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;
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") : "";
//...
}
I'm currently working with an application that has "swipey-tabs" and uses the following PagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new HomeFragment();
case 1:
return new ListFragment();
case 2:
return new ChartFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
I'm using the following code to communicate with one of my fragments from the main activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1)
{
if (resultCode == Activity.RESULT_OK)
{
String className = data.getExtras().getString("class_name");
if (className.trim().length() > 0) {
HomeFragment homeFrag = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.home_fragment);
if(homeFrag != null) {
Log.d("MainActivity", "homeFrag is not null");
homeFrag.newClass(className);
}else{
Log.d("MainActivity", "homeFrag is null");
HomeFragment newFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_fragment, newFragment);
transaction.commit();
newFragment.newClass(className);
}
addSubjectToDataBase(className);
}
}
}
}
My problem is that when I try to communicate with the fragment from the main activity, I seem to get multiple fragments existing at the same time. When I change the orientation of the screen or restart the activity, I get the modified version of the fragment, but when I swipe back and forth to view the fragments, I get the old, non-modified version of the fragment. The fragment manager doesn't seem to be registering the fragments created by the adapter because though I know the fragments have been created, the fragment manager always returns a null home fragment.
How should I go about avoiding this problem, and what is the best way to communicate with the fragment from the main activity?
After reading through this post I worked out a solution to my own question. The problem was that since FragmentPagerAdapter manages its own fragments, the fragment that I was trying to access wasn't the same as the one being used by the view pager.
I worked out a way of accessing the tags of the fragments that are used by the view pager by modifying my modifying my PagerAdapter as such:
public class TabsPagerAdapter extends FragmentPagerAdapter {
protected String homeTag;
protected String listTag;
protected String chartTag;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Log.d("Adapter", "returning new homeFragment");
return new HomeFragment();
case 1:
return new ListFragment();
case 2:
return new ChartFragment();
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
switch (position){
case 0:
homeTag = createdFragment.getTag();
break;
case 1:
listTag = createdFragment.getTag();
break;
case 2:
chartTag = createdFragment.getTag();
break;
}
return createdFragment;
}
public String getHomeTag(){
return homeTag;
}
public String getListTag(){
return listTag;
}
public String getChartTag(){
return chartTag;
}
#Override
public int getCount() {
return 3;
}
}
Then, it was a simple matter to modify my code to access the correct fragments after I had access the proper fragment tags:
HomeFragment homeFrag = (HomeFragment) getSupportFragmentManager().findFragmentByTag(mAdapter.getHomeTag());
if(homeFrag != null) {
Log.d("MainActivity", "homeFrag is not null");
homeFrag.newClass(className);
}else{
Log.d("MainActivity", "homeFrag is null");
HomeFragment newFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, newFragment, madapter.get);
transaction.commit();
newFragment.newClass(className);
It's not elegant but I would do something like this (Maybe someone will post a better solution):
In a singleton, I'll put an array of fragment:
public static Fragment[] sShownFragments = new Fragment[3];
Then in the getItem() method:
if(SingletonClass.sShownFragments[index]!=null){
return mFragments[index];
}
switch (index) {
case 0:
SingletonClass.sShownFragments[index] = new HomeFragment();
break;
case 1:
SingletonClass.sShownFragments[index] = new ListFragment();
case 2:
SingletonClass.sShownFragments[index] = new ChartFragment();
default:
SingletonClass.sShownFragments[index] = new Fragment();
}
return SingletonClass.sShownFragments[index];
Then in the getCount():
return SingletonClass.sShownFragments.length();
Now in your onActivityResult():
\\some code ...
((HomeFragment)SingletonClass.sShownFragments[0]).newClass(className);
\\ some other code...
I'm working with a bluetooth service in my application which ables me to get received message from another device. In my FragmentActivity, i'm using a handler to get this message:
FragmentActivity:
public final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
//my code
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
byte[] alpha = null;
alpha=readBuf;
if(alpha!=null){
//my code..
}
}
}
From this Handler I would like to get a data and transfer it to a Fragment.
I tried to use bundle but it doesn't work..
The code I tried:
In FragmentActivity:
Intent intent = new Intent();
intent.setClass(getApplicationContext(), General.class);
Bundle bundle=new Bundle();
bundle.putInt("battery", bat);
intent.putExtra("android.intent.extra.INTENT", bundle);
In Fragment:
Bundle bundle = getActivity().getIntent().getExtras();
if (bundle != null) {
int mLabel = bundle.getInt("battery", 0);
Toast.makeText(getActivity(), "tottiti: "+mLabel, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "prout", Toast.LENGTH_SHORT).show();
}
The application is returning "prout" which means that it can't get my data from my FragmentActivity.
Is there any other way to get a data frome a fragmentActivity and transfer it to a fragment?
Thank you for your help
Assuming that you need pass the data to the fragment at creation time, you could use setArguments() to pass data to the fragment, and getArguments() to read that data.
Bundle bundle = new Bundle();
bundle.putInt("battery", bat);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();
Then in onCreate() method of the fragment:
Bundle bundle=getArguments();
int mLabel = bundle.getInt("battery", 0);
But if the fragment is already created, then you could create a method inside the fragment that you'll use to pass data, something like this:
fragment.setBattery(bat);