我很難理解靜態變量。任何人都可以解釋爲什麼當我在FragmentJoy中調用變量'startingDate'時,它不會返回正確的值嗎?假設所有其他的代碼工作正常,而不是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
更好的方法是爲此創建接口。 –