• 8

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?

Either set the var as public static, or use

  • 95
Reply Report
      • 2
    • Setting the variable as static (like I had been doing) apparently causes a memory leak, according to an Android Studio lint warning. I'm going to use the latter approach.
      • 1
    • i was already using public static. problem was i was getting json data using volley. so i was trying to get view before data returned. i dont know what is memory lead anyhow. thanks

Using a public static variable isn't the best way to communicate between an activity and a fragment. Check out this answer for other ways:

The Android documentation recommends using an interface when the Fragment wants communicate with the Activity. And when the Activity wants to communicate with the Fragment, the Activity should get a reference to the Fragment (with findFragmentById) and then call the Fragment's public method.

The reason for this is so that fragments are decoupled from the activity they are in. They can be reused in any activity. If you directly access a parent Activity or one of its global variables from within a fragment, you are no longer able to use that fragment in a different Activity.

  • 17
Reply Report
      • 1
    • @ams92, Because the fragment would still have a dependency on the old activity. You would have to change the fragment code every time that you wanted to use it in a new activity.
***In your Activity
Bundle args = new Bundle();
args.putInt("something", Whatever you want to pass);

In your Fragment
 Bundle args = getArguments();
//whatever you want to get ,get it here.
//for example integer given     
    int index = args.getInt("index", 0);
  • 4
Reply Report