How to initialize menu library in Android - java

I want use this library for menu in my Application : GuillotineMenu-Android.
For close menu with onBackPress button i use this code :
#Override
public void onBackPressed() {
if (!isOpened) {
super.onBackPressed();
}
mGuillotineAnimation.close();
}
and set this codes to builder :
.setGuillotineListener(new GuillotineListener() {
#Override
public void onGuillotineOpened() {
isOpened = true;
}
#Override
public void onGuillotineClosed() {
isOpened = false;
}
})
Builder full code:
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.setGuillotineListener(new GuillotineListener() {
#Override
public void onGuillotineOpened() {
isOpened = true;
}
#Override
public void onGuillotineClosed() {
isOpened = false;
}
})
.build();
and write this code above of onCreate() method :
private GuillotineAnimation mGuillotineAnimation;
private boolean isOpened = true;
but when running application, and click onBackPress button show me this error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app, PID: 28891
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.app.Components.SlidingMenu.animation.GuillotineAnimation.close()' on a null object reference
at com.example.app.Activities.Category_page.onBackPressed(Category_page.java:256)
at android.app.Activity.onKeyUp(Activity.java:2506)
at android.view.KeyEvent.dispatch(KeyEvent.java:2633)
at android.app.Activity.dispatchKeyEvent(Activity.java:2757)
at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:543)
at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:53)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:312)
at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:53)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2297)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3995)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3957)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3488)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3541)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3507)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3515)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3488)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3541)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3507)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3617)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3515)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3674)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3488)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3541)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3507)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3515)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3488)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3541)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3507)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3650)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3811)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2242)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1883)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1874)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2219)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
I think i should Initialize mGuillotineAnimation in onCreate() method, but how can i initialize this?
Thanks all <3

You forgot to instanciate mGuillotineAnimation :
mGuillotineAnimation = new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.setGuillotineListener(new GuillotineListener() {
#Override
public void onGuillotineOpened() {
isOpened = true;
}
#Override
public void onGuillotineClosed() {
isOpened = false;
}
})
.build();

Related

Cannot get .edit() and .apply() to update values

I am new to Android Studio and learning how to create SharedPreference variables. I'm stuck that,updating the value of the string in SharedPreference raises a NullPointerException when I execute below code. Any help will be much appreciated. Thanks in advance.
This is my SettingPage
#Override //Creating the setting page
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settingpage);
setMinsBar = findViewById(R.id.numMinsBar);
setTimeEnterButton = findViewById(R.id.setTimeButton);
musicYesSwitch = findViewById(R.id.musicSwitch);
soundYesSwitch = findViewById(R.id.soundSwitch);
minsLeftTV = findViewById(R.id.minsLeftTV);
timerEndsTV = findViewById(R.id.timerEndsTV);
varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);
//Setting on click listener for the enter button for the time set
setTimeEnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timeInInt = Integer.parseInt(setMinsBar.getText().toString());
saveData();
}
});
}
public void saveData(){ //Declaring method saveData
varEditor = varAcrossApp.edit();
varEditor.putInt(timeInStringSP, timeInInt);
varEditor.putBoolean(musicYesSP, musicYesSwitch.isChecked());
varEditor.putBoolean(soundYesSP, soundYesSwitch.isChecked());
varEditor.apply();
Toast.makeText(getApplicationContext(), "Duration set", Toast.LENGTH_SHORT).show();
}
public void loadData(){ //Declaring method loadData
finalTimeInMins = varAcrossApp.getInt(timeInStringSP, 0);
musicYes = varAcrossApp.getBoolean(musicYesSP, false);
soundYes = varAcrossApp.getBoolean(soundYesSP, false);
}
public void updateView() {
minsLeftTV.setText(finalTimeInMins);
if (musicYes = true) {
timerEndsTV.setText("-Turn off music");
} else if (soundYes = true) {
timerEndsTV.setText("-Change sound profile to 'Sound'");
} else if (musicYes && soundYes) {
timerEndsTV.setText("-Turn off music /n-Change sound profile to 'Sound'");
} else {
timerEndsTV.setText("-Do nothing");
}
}
This is MainActivity
#Override //Creating the app here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
startButton = findViewById(R.id.startButton);
SettingPage settingPage = new SettingPage();
settingPage.loadData();
settingPage.updateView();
}
Error Code and Stack trace given below:
Process: com.example.sleep, PID: 6935
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sleep/com.example.sleep.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
at com.example.sleep.SettingPage.loadData(SettingPage.java:77)
at com.example.sleep.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7319) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
You should not call varAcrossApp.getInt before varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);
This is how shared preferences should/can be used in android.
class SettingsSpDao { // shared preferences data access object
private static final String SP = "SP";
private static final String MUSIC_YES = "music_yes";
public static boolean isMusicYes(Context context) {
// you can initialize sp beforehand so you don't have to pass in context but I prefer it this way, so I don't have to initialize it before using it
SharedPreferences sp = context.getSharedPreferences(SP, Context.MODE_PRIVATE);
return sp.getBoolean(MUSIC_YES , false);
}
// add your methods here
}
// call it anywhere as long as you can pass a context, such as Activity.
musicYes = SettingsSpDao.isMusicYes(this); // in your case `this` since it's in an Activity

RxJava Android caused ConcurrentModificationException

I'm a new in RxJava in Android development. I had changed in project AsyncTask to RxJava and got a ConcurrentModificationException. Yes, I used collection (sparseArray) but it doesn't matter 'cause exeption was thrown in findViewById.setVisibility. Only when I try to invoke setVisibility. I confused, what I do wrong? I have a TextView in fragment. At first I set up OnClickListener, in listener I init Single.fromCallable, then I set up OnDragListener
TextView tv;
tv.setOnClickListener(v -> {
if (isClickEnable) {
tv.setBackgroundResource(R.drawable.cheap_dark);
cheapInObservable(tv);
}
});
tv.setOnDragListener(new MyDragListener());
private void cheapInObservable(TextView tView) {
Single.fromCallable( () -> tView).subscribeOn(Schedulers.io())
.delay(250, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.doOnSuccess(this::onSuccessCheapIn)
.subscribe();
}
And in this code I get exeption:
private class MyDragListener implements View.OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event) {
View dragView = (View)event.getLocalState();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_ENDED:
if(!event.getResult()) {
if(dragView == v) {
dragView.setVisibility(View.VISIBLE);
activity.findViewById(sparseCheaps.get(dragView.getId())).
setVisibility(View.VISIBLE);
}
}
break;
private void onSuccessCheapIn(TextView tv) {
tv.setVisibility(View.INVISIBLE);
TextView tvd = activity.findViewById(sparseCheaps.get(tv.getId()));
tvd.setVisibility(View.VISIBLE);
AnimatorSet set = new AnimatorSet();
tvd.animate().rotation(0);
int up = activity.findViewById(R.id.guidelineGlowUp).getTop();
int left = getXcoord(tvd);
set.setDuration(400).playTogether(ObjectAnimator.ofFloat(tvd, TextView.TRANSLATION_X,
tvd.getX(), left),
ObjectAnimator.ofFloat(tvd, TextView.TRANSLATION_Y, tvd.getY(), up - 3));
set.setInterpolator(new AccelerateInterpolator((float) 0.4));
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
isAnimationCheaps = false;
super.onAnimationEnd(animation);
}
});
set.start();
}
I've found out that only the exeption is thrown when I use setVisibility. If I use AsyncTask instead of Rx it works without exception
StackTrace is:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:795)
at java.util.HashMap$KeyIterator.next(HashMap.java:822)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1154)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1156)
at android.view.ViewRootImpl.handleDragEvent(ViewRootImpl.java:4322)
at android.view.ViewRootImpl.access$1100(ViewRootImpl.java:103)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3407)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)

How Do I Cancel A Nested Timer?

I have a two timers:
theFirstCountDownTimer;
theGraceCountDownTimer;
I have a service that uses these two timers where the theGraceCountDownTimer is nested within theFirstCountdownTimer. On the OnDestroy Method, I want to cancel both timers.
private CountDownTimer theFirstCountDownTimer;
private CountDownTimer theGraceCountDownTimer;
//////////////////////////////////////
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
//////////////////////////////////////
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.i("Running", "The Service");
final SharedPreferences myPref = this.getSharedPreferences("testPref321", Context.MODE_PRIVATE);
theFirstCountDownTimer = new CountDownTimer(myPref.getInt("seekBar", 10000) * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String myMilis = Long.toString(millisUntilFinished);
Log.i("Timer One", "OnTick-" + myMilis);
}
#Override
public void onFinish() {
Log.i("Timer One", "OnFinish");
theGraceCountDownTimer = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
String myMilis = Long.toString(millisUntilFinished);
Log.i("Second Timer!", myMilis);
}
#Override
public void onFinish() {
Log.i("Finished!", "Heck Ya!");
}
}.start();
}
}.start();
return START_STICKY;
}
//////////////////////////////////////
#Override
public void onDestroy(){
theGraceCountDownTimer.cancel();
//This is the error
theFirstCountDownTimer.cancel();
super.onDestroy();
}
Additionally, I know the error is specifically with the line, theGraceCountDownTimer.cancel.
The error states:
Process: com.example.jackson.dmtapp, PID: 22854
java.lang.RuntimeException: Unable to stop service com.example.jackson.dmtapp.TheService#8090f39: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.CountDownTimer.cancel()' on a null object reference
at android.app.ActivityThread.handleStopService(ActivityThread.java:3479)
at android.app.ActivityThread.-wrap27(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1638)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.CountDownTimer.cancel()' on a null object reference
at com.example.jackson.dmtapp.TheService.onDestroy(TheService.java:93)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3462)
at android.app.ActivityThread.-wrap27(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1638) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6316) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
You need to call cancel() on both timer. Since you initialize theFirstCountDownTimer inside onStartCommand() so it can not be null. But theGraceCountDownTimer can be null as it initialize after theFirstCountDownTimer finished .
#Override
public void onDestroy(){
if(theGraceCountDownTimer!=null)
theGraceCountDownTimer.cancel();
theFirstCountDownTimer.cancel();
super.onDestroy();
}

App crashes when Progress Dialog is open and user changes orientation [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application has a Progress Dialog for login process and when the orientation is changed while dialog box is open, app crashes.This all works fine, except when screen orientation changes while the dialog is up. At this point the app crashes. I am figuring out this issue from the last 3 nights but not able to get it, please help.
My fragment:
public class Example extends Fragment {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
Unbinder unbinder;
#BindView(R.id.input_email) EditText _emailText;
#BindView(R.id.input_password) EditText _passwordText;
#BindView(R.id.btn_login) Button _loginButton;
#BindView(R.id.link_signup) TextView _signupLink;
#Override
public void onDestroyView() {
super.onDestroyView();
// unbind the view to free some memory
unbinder.unbind();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.Example, container, false);
unbinder=ButterKnife.bind(this,rootView);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent create= new Intent(getActivity(),NewAccount.class);
startActivity(create);
}
});
return rootView;
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
//new YourAsynTask(getActivity()).execute();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of loginFragment1");
super.onPause();
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
Intent i=new Intent(getActivity(),SuccessLogin.class);
startActivity(i);
}
public void onLoginFailed() {
Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
Logcat output:
11-16 19:20:10.955 4022-4022/com.example.a1332931.login_application E/WindowManager: android.view.WindowLeaked: Activity com.example.a1332931.login_application.TabActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{42b6135 V.E...... R......D 0,0-683,232} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.example.a1332931.login_application.Example.login(Example.java:156)
at com.example.a1332931.login_application.Example$1.onClick(Example.java:67)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-16 19:20:10.957 4022-4095/com.example.a1332931.login_application E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8aa6c60
11-16 19:20:12.512 4022-4022/com.example.a1332931.login_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1332931.login_application, PID: 4022
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at com.example.a1332931.login_application.Example.onLoginSuccess(Example.java:200)
at com.example.a1332931.login_application.Example$3.run(Example.java:168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Add this configuration change in your Android manifest activity:
<activity
android:name="YourActivity"
android:configChanges="orientation|keyboardHidden|screenSize"/>

How can I implement in fragment with my interface in another fragment

I created a interface in a fragment like following:
public interface SGFCallBackInterface {
void itemSelected(Item item);
}
private SGFCallBackInterface mCallbackInterface;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof SGFCallBackInterface) {
mCallbackInterface = (SGFCallBackInterface) context;
} else {
throw new RuntimeException(context.toString() + " must implement SelectGdsFragment.SGFCallBackInterface");
}
}
public void setSGFCallBackInterface(SGFCallBackInterface mCallbackInterface) {
this.mCallbackInterface = mCallbackInterface;
}
and I would implement that in another fragment like the following
public class SaleMenageFragment extends Fragment implements SelectGdsFragment.SGFCallBackInterface {
...
SelectGdsFragment selectGdsFragment = new SelectGdsFragment();
selectGdsFragment.setSGFCallBackInterface(SaleMenageFragment.this);
...
}
#Override
public void onItemSelected(Item item) {
...
}
But it's still not working, this is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.leo.test, PID: 3853
java.lang.RuntimeException: com.leo.test.Control.IndexActivity#2a66aece must implement SelectGdsFragment.SGFCallBackInterface
at com.leo.test.Control.Fragment.SaleManagement.SelectGdsClsFragment.onAttach(SelectGdsFragment.java:42)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019)
at android.support.v4.app.BackStackRecord.setLastIn(BackStackRecord.java:779)
at android.support.v4.app.BackStackRecord.calculateFragments(BackStackRecord.java:819)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:660)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I think the error log means my IndexActivity is not implementing SelectGdsFragment.SGFCallBackInterface.
But I don't want to implement that in IndexActivity.
I want to implement that in SaleMenageFragment.
How can I do that?
I am afraid you have to implement it in your Activity
See the doc
Communicating with Fragments
Hope it helps!
Just remove the part in onAttach(Context context) method like this:
public interface SGFCallBackInterface {
void itemSelected(Item item);
}
private SGFCallBackInterface mCallbackInterface;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof SGFCallBackInterface) {
mCallbackInterface = (SGFCallBackInterface) context;
} // this wont throw an exception if the activity does not implement that interface
}
public void setSGFCallBackInterface(SGFCallBackInterface mCallbackInterface) {
this.mCallbackInterface = mCallbackInterface;
}

Categories

Resources