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);
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;
I want to send intent from activity to fragment. I know how to send from fragment to activity just like this
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
but now i want to send from activity to fragment. I don't necessarily need to start the fragment i just want to make one of the id in my activity accessible in my fragment.
From your activity, you send your data, using bundle:
Bundle newBundle = new Bundle();
newBundle.putString("key", "text");
YourFragment objects = new YourFragment();
objects.setArguments(newBundle);
Your fragment class in onCreateView function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
if(getArguments() != null){
String yourText = getArguments().getString("key");
}
return inflater.inflate(R.layout.your_fragment, container, false);
}`
Passing the data from activity to fragment
Bundle bundle = new Bundle();
bundle.putString("params", "String data");
// set MyFragment Arguments
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
Receiving the data in the fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("params");
}
}
I am new to android and I am trying to call my MapFragment from adapter after on click using intent below is my code
Below is adapter code:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final BusInfo info = getItem(position);
View view = LayoutInflater.from(context).inflate(R.layout.bus_only_list,null);
TextView busname;
busname = (TextView) view.findViewById(R.id.busname);
busname.setText(info.name);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = context.getSharedPreferences("busInfo",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("bus_name",info.name);
editor.commit();
Intent intent = new Intent(context, MapsFragment.class);
intent.putExtra("name",info.name);
context.startActivity(intent);>
}
});
return view;
}
I want to pass to mapfragment using intent but it redirect to MainActivity instead of MapFragment. How can I stop transferring to MainActivity?
Thank you.
A common pattern to passing a value to a Fragment is using newInstance method. In this method you can set Argument to fragment as a means to send the value.
First, create the newInstance method:
public class YourFragment extends Fragment {
...
// Creates a new fragment with bus_name
public static YourFragment newInstance(String busName) {
YourFragment yourFragment = new YourFragment();
Bundle args = new Bundle();
args.putString("bus_name", busName);
yourFragment.setArguments(args);
return yourFragment;
}
...
}
Then you can get the value in onCreate:
public class YourFragment extends Fragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the value from arguments
String busName = getArguments().getString("bus_name", "");
}
...
}
You can set the value to the Fragment from your activity with:
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
YourFragment yourFragment = YourFragment.newInstance("bus_name_value");
fragTransaction.replace(R.id.fragment_place_holder, yourFragment);
fragTransaction.commit();
You can use the above codes to send the value in Fragment initialization.
If you want to set the value to the already instantiated fragment, you can create a method then invoke the method to set the value:
public class YourFragment extends Fragment {
...
public setBusName(String busName) {
// set the bus name to your fragment.
}
...
}
Now, In the activity, you can invoke it with:
// R.id.yourFragment is the id of fragment in xml
YourFragment yourFragment = (YourFragment) getSupportFragmentManager()
.findFragmentById(R.id.yourFragment);
yourFragment.setBusName("bus_name_value");
You cannot pass an intent to a Fragment. Try using a Bundle instead.
Bundle bundle = new Bundle();
bundle.putString("name", info.name);
mapFragment.setArguments(bundle)
In your Fragment (MapsFragment) get the Bundle like this:
Bundle bundle = this.getArguments();
if(bundle != null){
String infoName = bundle.getString("name");
}
As guys mentioned before:
1. Use callback or just casting on your context (your activity must handle changing fragments itself).
2. To change fragments use activity's FragmentManager - intent is used to start another activity.
Fragments Documentation
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);