i created an activity that contains 5 fragments and one of the fragments contains a profile page and i created another activity to edit the profile page but when i click the save button to return to the Edit (fragment) . The app crashes..
i need help or suggestions
this is my Fragment code below :
public class MeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.me, container, false);
Button bt = (Button) view.findViewById(R.id.btedit);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(), Editme.class);
startActivity(i);
}
});
return view;
}
and this is the Editme Class:
Button btnLoad = (Button) findViewById(R.id.btsave);
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
MeFragment save = new MeFragment();
fragmentTransaction.add(R.id.fragment_content, save);
fragmentTransaction.commit();
}
};
btnLoad.setOnClickListener(listener);
If you opened another activity and after making some changes you'd like to go back to previous activity(with 5 fragments) simply call finish method instead of doing fragment transaction.
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
Related
My MainActivity contain buttons which is used to switch to different fragments. Inside each fragment there are also has buttons. Activity button onClickListener work fine before implementing button onClickListener in fragments. I wonder if this is not supported by Android or my code is not correct.
Any pointer is appreciated. Thank you.
Fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = inflater.inflate(fragment1, container, false);
b2=(Button)v.findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
button2Clicked(v);
}
});
return inflater.inflate(R.layout.fragment1, container, false);
}
public void button2Clicked(View view){
//do something
}
Activity code:
public class MainActivity extends FragmentActivity {
private Button btnHealth;
private Button btnSetting;
private Button btnSleep;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Init component
btnHealth = (Button) findViewById(R.id.btnHealth);
btnSleep = (Button) findViewById(R.id.btnSleep);
btnSetting = (Button) findViewById(R.id.btnSetting);
replaceFragment(1);
btnHealth.setOnClickListener(new AdapterView.OnClickListener(){
#Override
//On click function
public void onClick(View view) {
replaceFragment(0);
}
});
btnSleep.setOnClickListener(new AdapterView.OnClickListener(){
#Override
//On click function
public void onClick(View view) {
replaceFragment(1);
}
});
btnSetting.setOnClickListener(new AdapterView.OnClickListener(){
#Override
//On click function
public void onClick(View view) {
replaceFragment(2);
}
});
}
//Create method replace fragment
private void replaceFragment(int pos) {
Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
fragment = new Fragment2();
break;
}
if(null!=fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
It is possible. If you want to handle the OnClick Event of the fragment inside the Activity class, you can do so by using FragmentInteractionListener (interface). Example: Android - handle fragment onClick from activity
On click of Button I am trying to open second fragment(YourResultFragment.java),
I had a lots but don't know why it is not working , here is my code which I am using
public class KnowYourBodyFragment extends Fragment {
public KnowYourBodyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_know_your_body, container, false);
Button button = (Button)rootView.findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Fragment mFragment = new YourResultFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.know_your_body_container, mFragment ).commit();
}
});
// Inflate the layout for this fragment
return rootView;
}
Use this Try to replace it with Default Container android.R.id.content.
Button button = (Button)rootView.findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment newFragment = new YourResultFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
// Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack("tag");
// Commit the transaction
transaction.commitAllowingStateLoss();
}
});
What is transaction.addToBackStack("tag") ?
Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
The buttons don't work when I change into landscape mode and back to portrait. Anyways, here is my code:
public class fragmentone extends Fragment {
Button biological;
Button natural;
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.firstlay, container, false);
biological = (Button) myView.findViewById(R.id.biological);
biological.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BiologicalHazards fragment = new BiologicalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
natural = (Button) myView.findViewById(R.id.natural);
natural.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NaturalHazards fragment = new NaturalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
return myView;
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
getActivity().setContentView(R.layout.firstlay);
}else{
getActivity().setContentView(R.layout.firstlay);
}
}
}
Does anyone know how to solve this? Any help is appreciated and thanks in advance.
you need to add setRetainInstance(true); //to your fragment onCreateView()
Also needn't be doing this getActivity().setContentView(R.layout.firstlay); in your onConfigurationChanged() method.
Hope this help :)
I think You to have re initilize when change orientation
try your modified code
private LayoutInflater inflater;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = inflater.inflate(R.layout.firstlay, container, false);
reInitilize(myView);
return myView;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
myView = inflater.inflate(R.layout.firstlay, null);
reInitilize(myView);
}else{
myView = inflater.inflate(R.layout.firstlay, null);
reInitilize(myView);
}
}
private void reInitilize(View myView) {
// TODO Auto-generated method stub
biological = (Button) myView.findViewById(R.id.biological);
biological.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BiologicalHazards fragment = new BiologicalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
natural = (Button) myView.findViewById(R.id.natural);
natural.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NaturalHazards fragment = new NaturalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
}
You don't need to do handle orientation your self just to change your layout. Create 2 files with this same name R.layout.fistlay. One in res/layout, one in res/layout-land. Android will automatically pick the right one base on the orientation.
you could implement the method
#Override
protected void onSaveInstanceState(Bundle bundle){
// store some variable like boolean, ints, String to the bundle
bundle.putBoolean('currentFragment', isInFragmentA);
// call the default method
super.onSaveInstanceState(bundle);
}
After this, you could check if you are on a configuration change as following:
void onCreate(Bundle bundle){
if (bundle == null){
//start the activity as the use is opening the app as normal
} else {
// bundle is not null
//get back the variable you have store and act accordingly
// e.g do some FragmentTransition
}
}
Hope this help
I have button in fragment1. I want to click this buttton and replace fragment1 by fragment2 but my app still close when I try to run it
This is my code in fragment1
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_menu, container, false);
// gallery = (Gallery) rootView.findViewById(android.R.id.list);
//gallery.setAdapter(new ItemAdapter(generateData(), getActivity()));
Button button = (Button) rootView.findViewById(R.id.imageButtonAll);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, homeFragment);
transaction.commit();
}
});
return rootView;
}
}
You cant open a fragment from inside another fragment.
So you have to move your code from the onClick to your activity and run it there.
In your Activity (lets assume its MainActivity):
public void openMyFragment(){
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, homeFragment);
transaction.commit();
}
And then, add this in your fragments onClick:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).openMyFragement();
}
});
The problem is that you are trying to replace a view that does not exist within the view that you are inflating. You have to switch these fragments from your FragmentActivity, which has the contentview containing the layout you are trying to replace.
MainActivity:
class MainActivity extends FragmentActivity {
public Fragment frag1;
public Fragment frag2;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
frag1 = new Frag1();
frag2 = new Frag2();
//assumption to switch to frag 1 immediately
switchToFragment(R.id.frame_container, homeFragment);
...
}
/** Switch UI to the given fragment (example) */
void switchToFragment(Fragment newFrag) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, newFrag)
.commitAllowingStateLoss();
currentFragment = newFrag;
}
}
Fragment:
....
final Activity activity = getActivity();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
about.setTextColor(Color.WHITE);
if(activity instanceof MainActivity) {
((MainActivity) activity).switchToFragment(((MainActivity) activity).frag1));
}
}
});
...
I'm trying to get back to a fragment from a fragmentActivity, but it is not working, I'm getting NullPointerException, When I hit cancel I need to update the previous fragment. How can I get back to a fragment and update it? don't know why this is happening.
public class AddEscolas extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addescola);
mSessao = new SecurePreferences(AddEscolas.this, "sessao");
pesquisa = (EditText) findViewById(R.id.campo_pesquisa);
nomeEscola = (TextView) findViewById(R.id.nomeEscola);
logradouro = (TextView) findViewById(R.id.endereco);
cidade = (TextView) findViewById(R.id.cidade);
procura = pesquisa.getText();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pesquisa.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
findViewById(R.id.btnProcurar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Pesquisa().execute();
mFerramentas.hideKeyboard(AddEscolas.this, pesquisa);
}
});
findViewById(R.id.btnCancelar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
}
}
FragmentClass :
public class EscolasFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_escolas, container, false);
ImageView add = (ImageView) rootView.findViewById(R.id.add);
mSessao = new SecurePreferences(getActivity(), "sessao");
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addIntent = new Intent(getActivity(), AddEscolas.class);
startActivity(addIntent);
}
});
return rootView;
}
}
Suppose you just need to call finish(), like this:
findViewById(R.id.btnCancelar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
The reason for the NullPointerException maybe is that the layout id of R.id.content_frame could not be found in the AddEscolas activity.
If you need to update the EscolasFragment fragment after the AddEscolas activity exits, you may do as follow steps:
use startActivity() from the EscolarFragment fragment to call the AddEscolas activity.
use onActivityResult() in the activity containing the EscolarFragment fragment to extract result returned by the AddEscolas activity.
use onResume() in the EscolarFragment fragment to update the UI.
You have wrong idea about what FragmentActivity is. Activities host fragments. You cant go to fragment without having activity. Read the docs
Null pointer exception comes from
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
you need to give instance to 'fragment'. Somehing like:
Fragment fragment = new YourFragment();
Simply call onBackPressed(); in the FragmentActivity.