当我试图从片段移动到活动时,我遇到了一个问题,但是它显示在堆栈跟踪下面。为什么getActivity()在Fragment中没有得到引用。主要是调用了下一个活动,但是当我对下一个活动进行意图动作时,却显示了此错误。
07-25 15:54:33.150 8662-8662/io.funswitch.gymmon E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.funswitch.gymmon, PID: 8662
java.lang.IllegalStateException: Fragment CheckInFragment{1fa737a} not attached to Activity
at android.support.v4.app.Fragment.startActivity(Fragment.java:1000)
at android.support.v4.app.Fragment.startActivity(Fragment.java:991)
at io.funswitch.gymmon.Fragments.CheckInFragment$1$1.onCallback(CheckInFragment.java:175)
at io.funswitch.gymmon.Fragments.CheckInFragment$6.onDataChange(CheckInFragment.java:507)
at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
当我不将活动附加到该片段时,我之前通过以下几行附加了MainActvity,则它显示了getActivity()== null。
public MainActivity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (MainActivity) context;
}
下面是我的Intent代码。在这里,我正在从片段变为活动。我也注册得最多。
readData(new MyCallback() {
@Override
public void onCallback(double value, double lng, String gymName) {
if (distance(value, lng, location.getLatitude(), location.getLongitude()) <= 0.1) {
LocalDate localDate = new LocalDate();
String date1 = localDate.toString();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
databaseReference.child("checkInStatus").setValue("1");
databaseReference.child("checInDate").setValue(date1);
databaseReference.keepSynced(true);
Intent intent = new Intent(activity, CheckOutActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else {
final Snackbar snackbar = Snackbar
.make(coordinatorLayout, getString(R.string.not_at_gym_location), Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
snackbar.setActionTextColor(Color.BLACK);
// Changing action button text color
View sbView = snackbar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.orange_bt));
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
}
});
请帮帮我。我没有找到解决其他帖子上搜索的方法的方法,但是没有帮助。