NullPointerException when passing variable data between fragments - java

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

Related

How to pass data from Activity A to fragment in Activity B?

I need to pass data from Activity "MainCalendar" to fragment "AddTaskFragment" in Activity "Add". I have a button in a fragment which opens an Activity "MainCalendar", where I select a date in the calendar, and then I need to send this date into a fragment.
When I click on Choose Button, there is opens a MainCalendar, where user need to choose date, after that, the activity closed, and than I want to put a date from MainCalendar to the text of "Choose Button".
Add Activity with a fragment,
MainCalendar Activity:MainCalendar
MainCalendar.class:
public class MainCalendar extends AppCompatActivity {
private CalendarView Calendar;
private String date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_calendar);
Calendar = (CalendarView) findViewById(R.id.calendarView);
Calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
date = (dayOfMonth+"/"+month+"/"+year);
System.out.println(date);
Intent intent = new Intent(MainCalendar.this, Add.class);
intent.putExtra("DATE_KEY", date);
finish();
}
});
}
Add.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setSelectedItemId(R.id.add);
Button notes_button = findViewById(R.id.notes_btn);
Button tasks_button = findViewById(R.id.tasks_btn);
Button goals_button = findViewById(R.id.goals_btn);
RadioButton rb = findViewById(R.id.choose_day_btn);
String date = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
date = extras.getString("DATE_KEY");
}
AddTasksFragment frag = new AddTasksFragment();
Bundle bundle = new Bundle();
bundle.putString("DATE_KEY", date);
frag.setArguments(bundle);
Fragment fragment1 = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment1).commit();
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notes:
startActivity(new Intent(getApplicationContext(), Notes.class));
overridePendingTransition(0,0);
return true;
case R.id.add:
return true;
case R.id.tasks:
startActivity(new Intent(getApplicationContext(), Tasks.class));
overridePendingTransition(0,0);
return true;
case R.id.goals:
startActivity(new Intent(getApplicationContext(), Goals.class));
overridePendingTransition(0,0);
return true;
case R.id.statistics:
startActivity(new Intent(getApplicationContext(), Statistics.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
tasks_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
notes_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddNotesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
goals_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddGoalsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
//
AddTaskFragment.class, which is in Add.class:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_tasks_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
subtask_btn = (Button) view.findViewById(R.id.add_subtask_btn);
subtask_name = (EditText) view.findViewById(R.id.subtask_name);
task_name = (EditText) view.findViewById(R.id.task_name);
lin_lay = (LinearLayout) view.findViewById(R.id.linear_layout);
sb_lay = (LinearLayout) view.findViewById(R.id.subtask_lay);
apply_btn = (Button) view.findViewById(R.id.apply_btn);
rgDay = (RadioGroup) view.findViewById(R.id.date_group);
rgPriority = (RadioGroup) view.findViewById(R.id.priority_group);
todayBtn = (RadioButton) view.findViewById(R.id.today_btn);
tomorrowBtn = (RadioButton) view.findViewById(R.id.tomorrow_btn);
chooseDayBtn = (RadioButton) view.findViewById(R.id.choose_day_btn);
lowPrBtn = (RadioButton) view.findViewById(R.id.low_btn);
mediumPrBtn = (RadioButton) view.findViewById(R.id.medium_btn);
highPrBtn = (RadioButton) view.findViewById(R.id.high_btn);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
dataBase = FirebaseDatabase.getInstance().getReference(TASKS_KEY);
this.getResources().getDisplayMetrics();
subtask_btn.setOnClickListener(this);
apply_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeTask();
}
});
chooseDayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MainCalendar.class);
startActivity(intent);
}
});
String data;
data = getActivity().getIntent().getStringExtra(DATE_KEY);
}
#Override
public void onClick(View v) {
addView();
}
private void writeTask() {
String Task;
Task = task_name.getText().toString();
dataBase.push().setValue(Task);
String[] subTasks = new String[sb_lay.getChildCount()];
for (int i = 0; i < sb_lay.getChildCount(); i++) {
View subtaskView = sb_lay.getChildAt(i);
EditText editTextName = (EditText) subtaskView.findViewById(R.id.subtask_name);
subTasks[i] = editTextName.getText().toString();
dataBase.child(Task).child("Subtasks").push().setValue(subTasks[i]);
}
dataBase.child(Task).push().setValue(getDay());
}
private String getDay(){
String day=null;
if(todayBtn.isChecked()){
Date currentTime = Calendar.getInstance().getTime();
day = currentTime.toString();
}
else if(tomorrowBtn.isChecked()){
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
day = dt.toString();
}else if(chooseDayBtn.isChecked()) {
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed ----------------------------------------------------------------------------" + day);
chooseDayBtn.setText(day);
}
return day;
}
private void addView(){
final View subtaskView = getLayoutInflater().inflate(R.layout.subtask_raw, null, false);
EditText editText = (EditText)subtaskView.findViewById(R.id.subtask_name);
ImageView imageClose = (ImageView)subtaskView.findViewById(R.id.remove_subtask);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(subtaskView);
}
});
sb_lay.addView(subtaskView);
String day;
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed " + day);
}
private void removeView(View view){
sb_lay.removeView(view);
}
As I understood, you Have to activities (Activity A and Activity B) and you have a fragment in Activity B. What you want to do is sending some data from activity A to that fragment for whatever reason.
Let's have a note first, You can't directly send data to any fragment of activity without launching it. So in order to send this data to the fragment you have to pass it from Activity A to Activity B as a first step and then send it from Activity B to the Fragment as a second step.
The type of data is very important. If you are sending a custom type (a model java class) you have to define it as Parcelable or if it is a primitive type such as int or float so you can send it directly
this is how to do it in Java
ActivityA.java
class ActivityA extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityA);
// define your data here
int data = 5;
// define an intent to send the data to the second activity
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("DATA_KEY", data);
startActivity(intent);
}
}
Then what we need to do is
receiving the data in the Activity B
Inflating the fragment
pass the data to the fragment
class ActivityB extends Activity{
Int data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityB);
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
data = extras.getInt("DATA_KEY");
}
// Fragment instance
FragmentClass frag = new FragmentClass();
Bundle bundle = new Bundle();
bundle.putInt("DATA_KEY", data );
frag.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, mFeedFragment);
fragmentTransaction.commit();
}
}
and then receive it the same way we received it in the Activity B

Null object reference when passing variable from activity to fragment

I am getting a null object reference when passing a variable from an activity to a fragment and I can't find out what the problem is. The variable I am trying to pass is currentPollName. Any help would be appreciated.
Here is the GroupActivity:
public class GroupActivity extends AppCompatActivity {
private ViewPager myViewPager;
private TabLayout myTabLayout;
private GroupTabsAccessorAdapter myTabsAccessorAdapter;
private String currentPollName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
currentPollName = getIntent().getExtras().get("pollName").toString();
Toast.makeText(GroupActivity.this, currentPollName, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("pollName", currentPollName);
PollFragment fragInfo = new PollFragment();
fragInfo.setArguments(bundle);
Toolbar toolbar = (Toolbar) findViewById(R.id.group_page_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(currentPollName);
myViewPager = (ViewPager) findViewById(R.id.group_tabs_pager);
myTabsAccessorAdapter = new GroupTabsAccessorAdapter(getSupportFragmentManager());
myViewPager.setAdapter(myTabsAccessorAdapter);
myTabLayout = (TabLayout) findViewById(R.id.group_tabs);
myTabLayout.setupWithViewPager(myViewPager);
}
public String getGroupName() {
return currentPollName;
}
}
Here is the PollFragment OnCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
pollView = inflater.inflate(R.layout.fragment_poll, container, false);
currentPollName = getArguments().getString("pollName");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
GroupNameRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(currentPollName);
InitializeFields();
RetrieveDisplayPollOptions();
newOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestNewPollOption();
}
});
submitOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SavePollOption();
}
});
return pollView;
}
Here is the Itent that starts the GroupActivity
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String currentPollName = list_view.getItemAtPosition(position).toString();
Intent pollIntent = new Intent(getContext(), GroupActivity.class);
pollIntent.putExtra("pollName", currentPollName);
startActivity(pollIntent);
}
});
I found the following things in the code
fragInfo Fragment is not passed to GroupTabsAccessorAdapter. So
add the fragment to the adapter and then write
myViewPager.setAdapter(myTabsAccessorAdapter);
In PollFragment move currentPollName =
getArguments().getString("pollName"); in onViewCreated as below.
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
currentPollName = getArguments().getString("pollName");
}`

Send String from Activity to Fragment

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

onclicklistener in fragment with intent

I have an an Android app with an Intro class.
This Intro class has got three fragments.
in fragment 3 (IntroPage3) i would like to set an onclicklistener with an intent form the IntroPage3 to Overview.class like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragementView = inflater.inflate(R.layout.intro_page1, container, false);
Button FinishIntroButton = (Button) FragementView.findViewById(R.id.FinishIntroButton);
FinishIntroButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(IntroPage3.this, Overview.class);
startActivityForResult(intent, 0);
}
});
return FragementView;
}
Problem: is this line:
intent = new Intent(IntroPage3.this, Intro.class);
Error message:
use intent = new Intent(getActivity(), Overview.class);
public class Fragment3 extends Fragment{
#Nullable
#Override
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.page_4, container, false);
Button button=view.findViewById(R.id.exit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
intent=new Intent(getActivity(),FragmentLogin.class);
startActivity(intent);
}
});
return view;
}
}
You must use getActivity() instead of IntroPage3.this
WHY
getActivity() in a Fragment returns the Activity the Fragment is currently associated with.
Button FinishIntroButton = (Button) FragementView.findViewById(R.id.FinishIntroButton);
FinishIntroButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(getActivity(), Overview.class);
startActivityForResult(intent, 0);
}
});

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