0

I have a fragment 'X' whose parent activity is 'A'.

I have another activity 'B' which contains a method 'getData()'; This activity also has its own parameterized constructor in which object of Context is being passed to this constructor.

Activity B:-

public class B
{
  Context _context;
  String val="XYZ";

  public B(Context context)
  {
    this._context = context;
    //Rest of the code
  }
  public String getData()
  {
    return val;
  }
}

My program requires me to call getData() method of activity 'B' in fragment 'X'

Fragment X :-

public class X extends Fragment implements 
{
  String name;

  Context context=getActivity().getApplicationContext();

  B obj1=new B(context); 
  //i have passed Context object from fragment X to Activity B

  ButtonClickEvent(..)
  {
    name=obj1.getData();
    //Rest of the code
  }
}

The issue is arising while launching Fragment X; the error is related to Context object, I dont understand what exatcly is the issue; Suggestions are welcome! Thanks.

Simran
  • 593
  • 1
  • 14
  • 37
  • Please post the error? Besides, why are you instantiating the activity with a constructor? Also, there should be some other way to get the data than to create a new instance of the activity and then getting its data from a fragment that is not attached to it. This could lead to subtle yet fatal bugs later on as your app grows. – Ishita Sinha Sep 21 '16 at 07:59

1 Answers1

2

Two likely definitions:

So create a constructor in Activity and pass getAcivity() there to get context.

Thanks.

Anshul Tyagi
  • 2,076
  • 4
  • 34
  • 65
  • Thanks your suggestion helped! context=getActivity().getApplicationContext(); I wrote this statement in OnCreateView() and it worked! – Simran Sep 21 '16 at 13:59