0

I'm trying to declare a global variable but without success. I was following this tutorial but this doesn't work if I want to transfer a variable from fragment to MainActivity.

First I added this code to my fragment class:

public class WebViewFragment extends Fragment{
private WebView myState;

public WebView getState(){
    return myState;
  }
  public void setState(){
    myState = webView;
  }

}

And then I added this to my MainActivity but it doesn't work:

WebViewFragment appState = ((WebViewFragment)getApplicationContext());
WebView state = appState.getState();

I get this error: Cannot cast from Context to WebViewFragment

Izak
  • 307
  • 5
  • 12

3 Answers3

2

Well, you are trying to cast the app context to a fragment, that can't work. You will have to look up the correct fragment with something like getFragmentManager().findFragmentById(R.id.my_fragment) and cast that.

In the tutorial he is using the app object, not a fragment. That's a bad idea and should be avoided if possible, since all variables that are inside the app object will not be garbage collected, filling up RAM.

meredrica
  • 2,563
  • 1
  • 21
  • 24
0

All you have to do is:

Put this in you Application class:

WebView state;
public WebView getState(){
    return myState;
}
public void setState(WebView webViewState){
    myState = webViewState;
}

Then in your fragment just do this to set the state:

getActivity().getApplicationContext().setSate(state);

And this in the activity to get the state:

getApplicationContext().getSate();

The above code should be divided so you can check if nothing is null.

Mikel
  • 1,581
  • 17
  • 35
  • I don't fully understand where to put the code. First part of the code that you said I have to put into Application class, which one do you mean? My MainActivity class or my fragment class? – Izak Oct 25 '13 at 11:39
  • none of those, as in the tutorial you have posted you should use a class that is subclass of Application and put that there. – Mikel Oct 25 '13 at 11:47
0

I had a similar issue and by reading through some of the comments I was able to provide a solution for one case. I had a custom adapter class that I was building and I needed to modify a global variable from that adapter class. My global variable was part of a Fragment that was attached to an Activity. Here's what I did:

In the Fragment I set the global variable:

public String myGlobalString = "initial_value";

In the adapter class that I was building, within the getView(...) function I had:

MyFragment myFragment = (MyFragment) ((MyActivity) context).getFragmentManager().findFragmentById(R.id.fragment_my_fragment);
myFragment.myGlobalString = "new_value";

This worked for me. I was trying to modify a value from an EditText within a ListView and so in my ListView adapater I added an addTextChangedListener and put my code within the onTextChanged function.

Brandon
  • 1,401
  • 1
  • 16
  • 25