Send String from Activity to Fragment - java

I try to pass a String from an Activity to a Fragment. As you can see I am using an if statement to prevent the app from crashing. The Toast message always shows 'Bundle null'. How can i prevent the bunde from being null?
Activity:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new SetttingsFragment())
.commit();
Bundle bundle = new Bundle();
bundleSettings.putString("my_bundle_key", "Bundle");
SetttingsFragment setttingsFragment = new SetttingsFragment();
setttingsFragment.setArguments(bundle);
Fragment:
public class SetttingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle bundle, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
Bundle bundle = getArguments();
if(bundle != null){
String bundleString = bundle.getString("my_bundle_key");
Log.i("my_bundle_key", bundleString);
} else{
Toast.makeText(getActivity(), "Bundle null", Toast.LENGTH_LONG).show();
}

In your code you are setting the bundle to a fragment variable that you are not using
create bundle
create fragment
set bundle in fragment
show fragment
this is the way you need to pass the arguments in fragment
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SettingsFragment settingsFragment = new SettingsFragment();
if (savedInstanceState == null) {
Bundle bundle = new Bundle();
bundle.putString("my_bundle_key", "Bundle");
settingsFragment.setArguments(bundle);
}
else {
settingsFragment.setArguments(savedInstanceState);
}
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, settingsFragment)
.commit();

In your activity you are creating two objects of fragment, second object where you are doing setargument is not attached to the view and not in use. Your fragment should be attached to the view like this:
Bundle bundle = new Bundle();
bundleSettings.putString("my_bundle_key", "Bundle");
SetttingsFragment setttingsFragment = new SetttingsFragment();
setttingsFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, setttingsFragment)
.commit();

You have to call Bundle before calling fragment like this following:
Bundle bundle = new Bundle();
bundleSettings.putString("my_bundle_key", "Bundle");
SetttingsFragment setttingsFragment = new SetttingsFragment();
setttingsFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, setttingsFragment)
.commit();

From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
Fragmentclass obj = new Fragmentclass();
obj .setArguments(bundle);
In Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

In Activity
AbcFragment fragment = AbcFragment .newInstance(**Value**);
getSupportFragmentManager.beginTransaction()
.replace(R.id.layout_container, fragment)
.commit();
In Fragment
public static AbcFragment newInstance(String Value) {
Bundle args = new Bundle();
args.putString("Value", Value);
AbcFragment fragment = new AbcFragment ();
fragment.setArguments(args);
return fragment;
}

You need to add it as arguments with Fragments and then can start fragment transactions to start the fragment.key used here is "input" and Here the example -
Bundle bundle = new Bundle();
bundle.putString("input", "dummy string args");
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
and the receive the arguments i.e input inside fragment , use it like -
String data = getArguments().getString("input")

Related

Starting a new Activity causes the app to restart

I've created a button which will open a new activity, but when I start the app and click on the button, the application just immediately restarts without any logcat errors. Here is my code:
public class amumu extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.amumu, container, false);
}
public void OnClickAmumuRunes(View view){
Intent GoToRunes = new Intent(view.getContext(), amumurunes.class);
startActivity(GoToRunes);
}
public void OnClickAmumuBuild(View view){
Intent GoToRunes = new Intent(view.getContext(), amumubuild.class);
startActivity(GoToRunes);
}
This is the code which I want to open, but I can't:
public class amumubuild extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.amumubuild, container, false);
}
}
and this is a fragmentclass where is tablayout in which first class is
public class FragmentClass extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragments);
initViews();
setuppager();
}
private void initViews(){
viewPager = findViewById(R.id.ViewPager);
tabLayout = findViewById(R.id.tab);
}
private void setuppager(){
PagerAdapter pagerAdapter = new SlideAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
public void OnClickDisplayToastAmumu(View view) {
Toast.makeText(this,"Amumu",Toast.LENGTH_SHORT).show();
}
public void OnClickDisplayToastLee(View view) {
Toast.makeText(this,"Lee Sin",Toast.LENGTH_SHORT).show();
}
public void OnClickDisplayToastPantheon(View view) {
Toast.makeText(this,"Pantheon",Toast.LENGTH_SHORT).show();
}
public void OnClickDisplayToastNami(View view) {
Toast.makeText(this,"Nami",Toast.LENGTH_SHORT).show();
}
You are using startActivity() to navigate to a Fragment. This doesn't work. You can only specify Activity classes in an Intent.
Additionally, make sure that you register each Activity in the AndroidManifext.xml file like this:
<application>
...
<activity android:name="com.example.SecondActivity">
</application>
Check out this post to see how to navigate between multiple Fragments in one Activity: How to start Fragment from an Activity
You can not start fragment by startActivity function so you need this:
private void loadFragment(final Fragment fragment) {
// load fragment
try {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.commit();
currentFragment = fragment;
} catch (Exception e) {
Log.d("mal", e.toString());
}
}

ActionBar Title not show for specific fragments

I've 4 different fragments, however it doesn't show the title for any of the fragments. When i created the fragments, everything was working fine, however now no title shows up on the actionBar. I've done all the changes which i found on the stackoverflow, but non of them worked for me
the code for my main activity is :-
private ActionBar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
toolbar.setTitle("Home");
loadFragment(new home());
BottomNavigationView navigation = (BottomNavigationView)findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment;
switch (menuItem.getItemId()){
case R.id.navigation_home:
toolbar.setTitle("Home");
fragment = new home();
loadFragment(fragment);
return true;
case R.id.navigation_dashboard:
toolbar.setTitle("Dashboard");
fragment = new Dashboard();
loadFragment(fragment);
return true;
case R.id.navigation_notifications:
toolbar.setTitle("Notifications");
fragment = new Notification();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
toolbar.setTitle("Profile");
fragment = new Profile();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
the code for one of the fragments which contains widgets(Rest of them are yet empty) is below :-
private OnFragmentInteractionListener mListener;
Button AskForHelp, Drafts, LogOut, Settings;
View view;
public Dashboard() {
// Required empty public constructor
}
public static Dashboard newInstance(String param1, String param2) {
Dashboard fragment = new Dashboard();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_dashboard, container,false);
AskForHelp = (Button)view.findViewById(R.id.askHelp);
AskForHelp.setOnClickListener(this);
Drafts = (Button)view.findViewById(R.id.drafts);
Drafts.setOnClickListener(this);
LogOut = (Button)view.findViewById(R.id.logOut);
LogOut.setOnClickListener(this);
Settings = (Button)view.findViewById(R.id.settings);
Settings.setOnClickListener(this);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.askHelp:
Intent intent = new Intent(getContext(), Questions.class);
startActivity(intent);
break;
case R.id.drafts:
Toast.makeText(getContext(),"Function not enabled", Toast.LENGTH_SHORT).show();
break;
case R.id.logOut:
Toast.makeText(getContext(),"Function not enabled", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(getContext(),"Function not enabled", Toast.LENGTH_SHORT).show();
break;
}
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
I've tried almost everything mentioned below. But it's still the same
In fragment just put this line in onCreatView so it will set your fragment title each time when you load your fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("you title here");
...
}

NullPointerException when passing variable data between fragments

I have 2 java classes (NewCard and inputText) with variable data which I would like to pass to a third class (FinalSubmit). I've done some research on how this is done and I think I've done everything I'm supposed to but when the target class tries to get the data, the app crashes due to a NullPointerException. Here are the onCreateView methods for the 3 classes.
NewCard:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_card, container, false);
ImageButton blueBtn = view.findViewById(R.id.blueButton);
ImageButton greenBtn = view.findViewById(R.id.greenButton);
ImageButton redBtn = view.findViewById(R.id.redButton);
blueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cardNumber = 1;
FinalSubmit fragment = new FinalSubmit();
Bundle bundle = new Bundle();
bundle.putInt("dataPointOne", cardNumber);
fragment.setArguments(bundle);
Toast.makeText(getContext(), "Blue", Toast.LENGTH_SHORT).show();
inputText fragment4 = new inputText();
FragmentTransaction ft4 = getFragmentManager().beginTransaction();
ft4.replace(R.id.frameLayout, fragment4, "FragmentName");
ft4.commit();
}
});
greenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cardNumber = 2;
inputText finalSubmit = new inputText();
Bundle bundle = new Bundle();
bundle.putInt("dataPointOne", cardNumber);
finalSubmit.setArguments(bundle);
Toast.makeText(getContext(), "Green", Toast.LENGTH_SHORT).show();
inputText fragment4 = new inputText();
FragmentTransaction ft4 = getFragmentManager().beginTransaction();
ft4.replace(R.id.frameLayout, fragment4, "FragmentName");
ft4.commit();
}
});
redBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cardNumber = 3;
FinalSubmit fragment = new FinalSubmit();
Bundle bundle = new Bundle();
bundle.putInt("dataPointOne", cardNumber);
fragment.setArguments(bundle);
Toast.makeText(getContext(), "Red", Toast.LENGTH_SHORT).show();
inputText fragment4 = new inputText();
FragmentTransaction ft4 = getFragmentManager().beginTransaction();
ft4.replace(R.id.frameLayout, fragment4, "FragmentName");
ft4.commit();
}
});
return view;
}
The part dealing with data passing is the
FinalSubmit fragment = new FinalSubmit();
Bundle bundle = new Bundle();
bundle.putInt("dataPointOne", cardNumber);
fragment.setArguments(bundle);
inputText
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_input_text, container, false);
final EditText editText = (EditText) view.findViewById(R.id.text);
String cardText = editText.getText().toString();
Button submit = view.findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), editText.getText().toString(), Toast.LENGTH_SHORT).show();
FinalSubmit finalSubmit = new FinalSubmit();
Bundle bundle = new Bundle();
bundle.putString("dataPointTwo", editText.getText().toString());
finalSubmit.setArguments(bundle);
recordAudio fragment5 = new recordAudio();
FragmentTransaction ft5 = getFragmentManager().beginTransaction();
ft5.replace(R.id.frameLayout, fragment5, "FragmentName");
ft5.commit();
}
});
return view;
}
Data passing part:
FinalSubmit finalSubmit = new FinalSubmit();
Bundle bundle = new Bundle();
bundle.putString("dataPointTwo", editText.getText().toString());
finalSubmit.setArguments(bundle);
Final Submit:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_final_submit, container, false);
final TextView info = view.findViewById(R.id.info);
Button finalSubmit = view.findViewById(R.id.finalS);
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = getArguments();
int cardNumber = bundle.getInt("dataPointOne", 0);
String inputText = bundle.getString("dataPointTwo", "");
info.setText(cardNumber+" "+inputText);//+inputText);
}
});
return view;
}
The exception occurs when trying to get the data here:
Bundle bundle = getArguments();
int cardNumber = bundle.getInt("dataPointOne", 0);
String inputText = bundle.getString("dataPointTwo", "");
Logcat:
06-15 12:53:44.064 16325-16325/com.parrotcards.kyle.parrotcards E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.parrotcards.kyle.parrotcards, PID: 16325
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
at com.parrotcards.kyle.parrotcards.FinalSubmit$1.onClick(FinalSubmit.java:42)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19884)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
According to my research I should have done everything right, so I would really appreciate if someone could point out what I've done wrong here. Thanks a million!
Your problem here, you create a FinalSubmit with bundle what contain an Int value
But here, you create a new one and set a String value..
So you need to pass bundle with Int value to your inputText and then add to it String value.
Try to use sharedPreference, something like this:
blueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cardNumber = 1;
FinalSubmit fragment = new FinalSubmit();
Toast.makeText(getContext(), "Blue", Toast.LENGTH_SHORT).show();
getContext().getSharedPreferences("pref",0)
.edit().putInt("int",cardNumber).apply();
FragmentTransaction ft4 = getFragmentManager().beginTransaction();
ft4.replace(R.id.frameLayout, fragment4, "FragmentName");
ft4.commit();
}
});
And extract it
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cardNumber= getContext().getSharedPreferences("pref",0)
.getInt("int",0);
}
});
And all the same with String value)
you must have to try intent instead put this code in newcard.java when onclick event call it will pass your data from current class to another class
Intent i = new Intent(MainActivity.this,Filesubmit.class);
i.putExtra("value", cardText);
and second activity you can access your value with
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("value");
here is a link for more here

How to call other fragment from image view onclicklistener

I want to call class FragmentDiagnosis from image view click listener. Im so confused about how to call the other class from click listener? I've tried use intent, but there was error on it. For anyone who understand about this problem, please help me. I will appreciate it, thank you so much.
package com.pakarayam;
import android.app.Fragment;
public class FragmentHome extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.activity_fragment_home, container, false);
configureImageView(view);
return view;
}
private void configureImageView(View view) {
// TODO Auto-generated method stub
ImageView mulai = (ImageView) view.findViewById(R.id.mulai);
mulai.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent iMulai = new Intent(getApplicationContext(), FragmentDiagnosis.class);
startActivity(iMulai);
}});
}}
try this:
public void onClick(View v)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
YourFragment yourFragment= new YourFragment();
fragmentTransaction.add(R.id.your_activity_id, yourFragment, "FRAGMENT");
fragmentTransaction.commit();
}
#SuppressLint("NewApi")
public void addFragment(Fragment fragment, Bundle bundle) {
try {
if (bundle != null) {
fragment.setArguments(bundle);
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_left,
R.anim.slide_right, R.anim.slide_left, R.anim.slide_right);
fragmentTransaction.add(R.id.frame1, fragment).addToBackStack(null)
.commit();
} catch (Exception e) {
Log.e("MenuChangeActivity", "Add fragment error");
}
}

android send data to fragment from activity

I have a map activity. When I click on the info window of the marker an intent will send the id to my fragment. In my map activity :
map.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m) {
Intent nextScreen = new Intent (Map.this,
PHDetail.class);
Bundle bundle = new Bundle();
bundle.putString("test", "id");
Callfor c = new Callfor();
c.setArguments(bundle);
startActivityForResult(nextScreen, 101);
}
});
In my fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_call_for, container, false);
TextView TXT = (TextView) rootView.findViewById(R.id.test);
Bundle test = getArguments();
if(test!=null){
String d = test.getString("test", " ");
TXT.setText(d);
}
return rootView;
}
The problem is the bundle is null. How can I fix this?
This is my PHDetail FragmentActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.phdetail);
Intent intent = getIntent();
if (intent != null) {
String id = intent.getStringExtra("test");
}
// Initialization :
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs :
for (String tab_name : tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
UPDATE
On your onTabSelected you need to create your Fragment, set the bundle and then do the transaction like this.
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
Bundle bundle = new Bundle();
bundle.putString("id", id);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);
ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();
}
FIRST ANSWER
The right way to pass values to other Activities like a FragmentActivity it´s adding those values to the intent that´s going to start them.
map.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m) {
Intent nextScreen = new Intent (Map.this, PHDetail.class);
intent.putExtra("test", "id");
startActivityForResult(nextScreen, 101);
}
});
Then on your FragmentActivity called PHDetail you should get the values from the Intent.
Intent intent = getIntent();
if (intent != null) {
String id = intent.getStringExtra("test");
}
After that when you load your Fragment on your container view on PHDetail, you should add the Bundle and then do the transaction.
Bundle bundle = new Bundle();
bundle.putString("test", "id");
Callfor c = new Callfor();
c.setArguments(bundle);
After that you'll be able to retrieve the values inside your Fragment like you stated above
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_call_for, container, false);
TextView TXT = (TextView) rootView.findViewById(R.id.test);
Bundle test = getArguments();
if(test!=null){
String d = test.getString("test", " ");
TXT.setText(d);
}
return rootView;
}
Hope it helps! :)

Categories