我很难尝试理解静态变量。任何人都可以解释为什么当我调用变量' startingDate'在FragmentJoy中,它没有返回正确的值?假设所有其余代码都运行正常,而不是NULL值和databaseCategories工作正常。如何在“onDataChange()'内部保存值?方法并在FragmentJoy中使用它?
我不能删除:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {)
这是仪表板活动
public class Dashboard extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
static String startingDate;
DatabaseReference databaseCategories;
ArrayList<Category> currentJoyCategories;
User currentUser; //holds the information of the current user
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
. . . . . .
databaseCategories = FirebaseDatabase.getInstance().getReference("Categories");
currentJoyCategories = new ArrayList<>();
databaseCategories.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//want to do
startingDate = "some string";
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} //end of Dashboard class
在我要做的另一个课程中:
public class FragmentJoy extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_joy,container,false);
//not storing the string "some string"
System.out.println("testing " + Dashboard.startingDate);
return view;
} //end of onCreateView method
} //end of class
答案 0 :(得分:2)
您需要将startingDate
声明为public static String startingDate
使用此
public static String startingDate;
而不是
static String startingDate;
然后您可以在FragmentJoy
这样的
Log.e("testing ",Dashboard.startingDate);
答案 1 :(得分:0)
在这里,我向您展示如何将一个class
的静态方法用于另一个类。
e.g。我在类HomeFragment
中定义了一个静态方法,
public class HomeFragment扩展了BaseFragment {
Unbinder unbinder;
int mode;
public static HomeFragment getInstance(int mode) {
HomeFragment homeFragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(KeyUtil.KEY_MODE, mode);
homeFragment.setArguments(bundle);
return homeFragment;
}
....................
}
而且,我在我的static
课程中使用了这个MainActivity
方法,
public class MainActivity extends AppCompatActivity {
...........................
/**
* Get the fragment while need to push.
*
* @return: fragment
*/
private Fragment openFragment() {
switch (navItemIndex) {
case 0:
// Here I have called static method
return HomeFragment.getInstance(0);
}
}
........................
}