I'm passing a string between two fragments. It's working but for a reason i can't get the string outside onStart...
public class EventSelectFriendFragment extends Fragment {
final static String DATA_RECEIVE = "data_receive";
String passedPushId;
Button create;
#Override
public void onStart() {
super.onStart();
Bundle args = getArguments();
if (args != null) {
passedPushId = args.getString(DATA_RECEIVE);
Log.d("passed id",args.getString(DATA_RECEIVE) );
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_event_select_friend, container, false);
create= (Button) rootView.findViewById(R.id.btnCreate);
btnMaakEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for(int i = selectedFriends.size()-1 ; i >= 0; i--){
Log.d("array: ", i + selectedFriends.get(i).getFirstName());
Log.d("passedPushId: ", passedPushId);
}
}
});
return rootView;
}
}
In onStart passedPushId gives me the string from the other fragment.
But when i want to use it in a for loop the passedPushId is null...
onCreateView() is called earlier than onStart(). Generally speaking, you should initialize instance variables from the arguments Bundle inside of onCreate(), not onStart(), as that is much earlier in the fragment lifecycle.
Related
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileFragment myFragment = new ProfileFragment();
ProfileFragment.profileFragment.getFragmentManager().beginTransaction().replace(R.id.RelLayout1, myFragment).addToBackStack(null).commit();
Log.d(TAG, "onClick: rr");
}
});
This is called inside a Recyclerview Adapter.On clicking an item ,I want to create a new instance of the fragment and hide some of the views inside the created Fragment.
You can send flag on fragment arguments and check this flag on the fragment class
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileFragment myFragment = new ProfileFragment();
Bundle fragmentBundle = new Bundle();
fragmentBundle.putBoolean(ProfileFragment.MY_FLAG, true);
myFragment.setArguments(fragmentBundle);
ProfileFragment.profileFragment.getFragmentManager().beginTransaction().replace(R.id.RelLayout1, myFragment).addToBackStack(null).commit();
}
});
And now you can check this flag in your fragment class
public class ProfileFragment extends Fragment{
public static final String MY_FLAG = "MY_FLAG";
private boolean hideShowFlag = false;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check if arguments not null and contains the desired key
//if all true set value to a variable to be used later
if (getArguments() != null && getArguments().containsKey(MY_FLAG) {
this.hideShowFlag = getArguments().getBoolean(MY_FLAG);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mView = inflater.inflate(getRootView(), container, false);
if (this.hideShowFlag) {
//write your logic for show and hide here
}
return mView;
}
}
hope my answer will help you.
I am trying to get some text from editTexts on different fragments. So what I do first is define my mPager and mPagerAdapter:
a_Atenuacion Activity
public class a_Atenuacion extends FragmentActivity{
private static final int NUM_PAGES = 3;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_dat_viewpager);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new a_Dat_Inicio1();
case 1:
return new a_Dat_Inicio2();
case 2:
return new a_Dat_Inicio3();
}
return null;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
Then I get my 3 fragments classes (Both 1st and 2nd layouts have an editText, but the 3rd one has an editText and a button). The button function is that when I am in the last fragment (fragment3) it take info form (different editTexts) and send to another activity.
a_Dat_Inicio1 Fragment
public class a_Dat_Inicio1 extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_dat_inicio1, container, false);
return view;
}
}
a_Dat_Inicio3 Fragment
public class a_Dat_Inicio3 extends Fragment {
EditText edit3;
EditText edit2;
EditText edit1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.a_dat_inicio3, container, false);
edit1 = (EditText)getActivity().findViewById(R.id.editText1);
final String edit11 = edit1.getText().toString();
edit2 = (EditText)getActivity().findViewById(R.id.editText2);
final String edit22 = edit2.getText().toString();
edit3 = (EditText)view.findViewById(R.id.editText3);
final String edit33 = edit3.getText().toString();
Button but=(Button) view.findViewById(R.id.button);
but.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//Creamos el bundle
Bundle bundle = new Bundle();
//Le ponemos la variable parametro con el contenido (key, valor)
bundle.putString("edit3", edit33);
bundle.putString("edit2", edit22);
bundle.putString("edit1", edit11);
Intent net= new Intent(v.getContext(),Prueba1.class);
net.putExtras(bundle);
startActivity(net);
}
});
return view;
}
}
Finally I get bundle on another activity (Prueba1.class) and it is curious that I only get result for editText1 (on 1st fragment) and rest are null.
Can anybody give me a help?
Thanks in advance.
finally I get over an interface, that is the only way I think to get soemthing on already defined fragments.
My code get like this:
1st define an interface
public interface OnEditTextChanged {
public void onEditPressed1(String edit1);
public void onEditPressed2(String edit1);
public void onEditPressed3(String edit1);
Then fragment activity:
public class a_Dat_Inicio1 extends Fragment {
EditText edit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_1dat_inicio1, container, false);
init (view);
return view;
}
OnEditTextChanged editListener;
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
editListener=(OnEditTextChanged) getActivity();
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()+"must implemnt onEditPressed");
}
}
private void init(View view) {
edit=(EditText) view.findViewById(R.id.editText1);
//cada vez que se modifique texto llamar
edit.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
final String edit11 = edit.getText().toString();
editListener.onEditPressed1(edit11);
}
});
And finally on our main activity, call the method:
public class a_Atenuacion extends FragmentActivity implements OnEditTextChanged {
String dat1;
String dat2;
String dat3;
private static final int NUM_PAGES = 3;
private PagerAdapter mPagerAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_1dat_viewpager);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
//HERE DO WHATEVER YOU WANT WITH THE DATA CAUGTH ON THE EDIT 1 METHOD
}
#Override
public void onEditPressed1(String edit1) {
if(mPager.getCurrentItem()==0){
dat1=edit1;
Toast bread = Toast.makeText(getApplicationContext(), "edit1", Toast.LENGTH_LONG);
bread.show();
}
}
HOPE this help someone!!!
In any way thanks!!!
Try this:
In your second fragment, pass the intent extras and your value. For example:
In you second fragment, do this :
Intent someintent = new Intent();
//Some first result
someintent.putExtra("your_value_one", your_value_one);
//Some Second result
someintent.putExtra("your_value_two", your_value_two);
//Some third result
someintent.putExtra("your_value_three", your_value_three);
getActivity().setResult(getActivity().RESULT_OK,someintent);
getActivity().finish();
In your other fragment, where you want this result, do this on your other fragment like this:
1) Make some method to get the info.
private void getInfo() {
//Note: The values are coming from a diff activity or fragment and so the strings should match.
Intent data = new Intent();
String first_value = data.getStringExtra("your_value_one");
String second_value = data.getStringExtra("your_value_two");
String third_value = data.getStringExtra("your_value_three");
Log.i("First Value: ", first_value);
Log.i("First Value: ", second_value);
Log.i("First Value: ", third_value);
}
After making this method, just call it on your onActivityCreated().
Now you can use those string however and wherever you want to. If you want to use those values anywhere else, make sure to define you strings at the very start so that you can use the values anywhere.
Hope this answer helps .. :)
I create test empty fragment. It don't have any element, return null. Then I run application. In initial orientation all work good.
static FragmentTransaction fragment_trans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableClassFragment tableFragment = new TableClassFragment(12);
fragment_trans = getFragmentManager().beginTransaction();
fragment_trans.add(R.id.tableFragment, tableFragment);
fragment_trans.commit();
}
static class TableClassFragment extends Fragment {
int table_size;
String[] sequence_letters_in_table = {};
public TableClassFragment(int _size){
table_size = _size;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return null;
}
}
When I changed orientation - get error
FATAL EXCEPTION: main
Process: bairro.lettersgenerator, PID: 2885
java.lang.RuntimeException: Unable to start activity ComponentInfo{bairro.lettersgenerator/bairro.lettersgenerator.MainActivity}:
android.app.Fragment$InstantiationException: Unable to instantiate fragment bairro.lettersgenerator.MainActivity$TableClassFragment: make sure class name exists, is public,
and has an empty constructor that is public
Caused by: java.lang.InstantiationException: can't instantiate class bairro.lettersgenerator.MainActivity$TableClassFragment;
no empty constructor
Please help
InstantiationException: [...] TableClassFragment;
no empty constructor
You TableClassFragment should have "an empty constructor":
static class TableClassFragment extends Fragment {
int table_size;
String[] sequence_letters_in_table = {};
public TableClassFragment() {
// ...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return null;
}
}
Use Fragment.setArguments() to pass arguments to it.
You need an empty constructor in your fragment, that's why you are getting this error.
Like:
public TableClassFragment(){
}
pass table_size to TableClassFragment as Bundle
TableClassFragment tableFragment = new TableClassFragment();
Bundle bunble =new Bundle();
bunble.putInt(TableClassFragment.ARG_TABLESIZE , 12);
tableFragment setArguments(bundle);
change TableClassFragment
public class FaceScanExampleFragment extends Fragment{
final static String ARG_TABLESIZE = "table_size";
int table_size;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
......
if (savedInstanceState != null) {
table_size = savedInstanceState.getInt(ARG_TABLESIZE);
}
......
}
#Override
public void onStart() {
super.onStart();
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_TABLESIZE));
} else
}
}
public void updateArticleView(int position) {
table_size = position;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_TABLESIZE, table_size);
}
Try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, container, false);
Toast.makeText(getActivity(), "FirstFragment.onCreateView()",
Toast.LENGTH_LONG).show();
return rootView;
}
}
Hello I am using Fragment in my android application. I need to get the view which I can get using.
mNoteEditText = rootView.findViewById(R.id.noteEditText);
This mNoteEditText is require to access in onBackPressed so every view reference I need to make them static variable because of Fragment class is static. I know to make every view to static variable is not good approach. How this I can make such that I dont need to make any static variable of the view.
public class NotesActivity extends Activity {
private int bookId;
private int chapterId;
private static EditText mNoteEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
// get data from intent that sent from home activity
bookId = getIntent().getIntExtra("book_id", -1);
chapterId = getIntent().getIntExtra("book_id", -1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new NoteFragment()).commit();
}
}
/**
* A note fragment containing a note layout.
*/
public static class NoteFragment extends Fragment {
public NoteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes,
container, false);
mNoteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
return rootView;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
// get database instance
MySQLiteOpenHelper db = MySQLiteOpenHelper.getInstance(this);
Notes note = new Notes();
note.setBookId(bookId);
note.setChapterId(chapterId);
note.setNote(mNoteEditText.getText().toString());
}
}
Please help and thanks in advance.
A Fragment has a Method called getView(). With it you can get the View of the Fragment as long as it is attached to an Activity.
View view = fragment.getView();
But if you are looking for a View inside the Fragment you can also just get it with findViewById() from the Activity. Again the Fragment has to be attached to the Activity for this to work.
BUT you should not do that. Nothing outside the Fragment should have anything to do with something inside the Fragment. Write public methods in the Fragment to interact with it. Try something like this:
public static class NoteFragment extends Fragment {
private EditText noteEditText;
public NoteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
this.noteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
return rootView;
}
// I added the following 3 methods to interact with the Fragment
public boolean isEmpty() {
final String text = this.noteEditText.getText().toString();
return text.isEmpty();
}
public String getText() {
return this.noteEditText.getText().toString();
}
public void setText(String text) {
this.noteEditText.setText(text);
}
}
And now in your Activity you can do this:
public class NotesActivity extends Activity {
private int bookId;
private int chapterId;
private NoteFragment noteFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
// get data from intent that sent from home activity
bookId = getIntent().getIntExtra("book_id", -1);
chapterId = getIntent().getIntExtra("book_id", -1);
if (savedInstanceState == null) {
this.noteFragment = new NoteFragment();
getFragmentManager().beginTransaction().add(R.id.container, this.noteFragment).commit();
}
// Now you can interact with the Fragment
this.noteFragment.setText("some text");
...
if(!this.noteFragment.isEmpty()) {
String note = this.noteFragment.getText();
...
}
}
}
I have FragmentTabHost with 2 tabs.
Each fragment (tab) need to load data from internet and display it.
If I am loading data onCreate and populating it then switching to another tab and back i have empty views.
TextView emailView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View convertView = inflater.inflate(R.layout.contactdetails_pro, container, false);
emailView = (TextView) convertView.findViewById(R.id.contactdetails_info_email);
return convertView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String id = getArguments().getString("id");
MyTask pdthread = new MyTask(this.getActivity(), id, new AsyncTaskCompleteListener() {
#Override
public void onComplete(Detail detail) {
emailView.setText(detail.getEmail());
}
});
pdthread.execute();
}
I'm not familiar with FragmentTabHost but you can try this (note: you may have to make the Detail class implement Serializable):
Detail mDetail = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String id = getArguments().getString("id");
if (savedInstanceState == null) {
MyTask pdthread = new MyTask(this.getActivity(), id, new AsyncTaskCompleteListener() {
#Override
public void onComplete(Detail detail) {
mDetail = detail;
emailView.setText(mDetail.getEmail());
}
});
pdthread.execute();
} else {
mDetail = (Detail)savedInstanceState.getSerializable("detail");
if (mDetail ! = null) {
emailView.setText(detail.getEmail());
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("detail", mDetail);
}