Single Activity With 3 Fragments Crashing

I have created an Authentication Activity, which has a FrameLayout as a container in which I replace the corresponding fragments the user wants to use.

The first fragment in the container is the WelcomeFragment, which is just a ConstraintLayout with a background, an ImageView for the Logo and two buttons to move to the LoginFragment or SignUpFragment.

The issue is that, when I go from the WelcomeFragment to the LoginFragment, come back to the WelcomeFragment, go to the SignUpFragment, and try to comeback again to the WelcomeFragment, the App crashes, and gives me the following error:

Stack Trace of Error:

12-31 18:44:45.558 4367-4367/com.nopeia.fitassistant E/MessageQueue-JNI: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class
<unknown>
  at android.view.LayoutInflater.inflate(LayoutInflater.java:539) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at com.nopeia.fitassistant.ui.authentication.welcome.WelcomeFragment.onCreateView(WelcomeFragment.java:50) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
  at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:857) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2577) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
  at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322) at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:851) at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:794)
  at android.support.v4.app.FragmentActivity.onBackPressed(FragmentActivity.java:174) at android.app.Activity.onKeyUp(Activity.java:2482) at android.view.KeyEvent.dispatch(KeyEvent.java:2665) at android.app.Activity.dispatchKeyEvent(Activity.java:2735)
  at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534) at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58) at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:316)
  at com.android.internal.policy.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2352) at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4206) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4168)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3709)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3828)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3709) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3885) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3709) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3861) at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4022) at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2257)
  at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1878) at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1869) at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2234)
  at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:1 12-31 18:44:45.559 4367-4367/com.nopeia.fitassistant E/AndroidRuntime: FATAL EXCEPTION: main Process: com.nopeia.fitassistant, PID: 4367 android.view.InflateException:
  Binary XML file line #0: Binary XML file line #0: Error inflating class
  <unknown>
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at com.nopeia.fitassistant.ui.authentication.welcome.WelcomeFragment.onCreateView(WelcomeFragment.java:50) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
    at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:857) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2577) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322) at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:851) at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:794)
    at android.support.v4.app.FragmentActivity.onBackPressed(FragmentActivity.java:174) at android.app.Activity.onKeyUp(Activity.java:2482) at android.view.KeyEvent.dispatch(KeyEvent.java:2665) at android.app.Activity.dispatchKeyEvent(Activity.java:2735)
    at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534) at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58) at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:316)
    at com.android.internal.policy.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2352) at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4206) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4168)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3709)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3828)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3709) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3885) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3709) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3682) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3735)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3701) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3861) at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4022) at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2257)
    at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1878) at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1869) at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2234)
    at android.view.Inp

AuthenticationActivity.class :

package com.nopeia.fitassistant.ui.authentication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.nopeia.fitassistant.R;
import com.nopeia.fitassistant.ui.authentication.login.LoginContract;
import com.nopeia.fitassistant.ui.authentication.login.LoginFragment;
import com.nopeia.fitassistant.ui.authentication.signup.SignUpContract;
import com.nopeia.fitassistant.ui.authentication.signup.SignUpFragment;
import com.nopeia.fitassistant.ui.authentication.welcome.WelcomeContract;
import com.nopeia.fitassistant.ui.authentication.welcome.WelcomeFragment;
import com.nopeia.fitassistant.ui.myzone.MyZoneActivity;
import com.nopeia.fitassistant.util.ActivityUtils;

import javax.inject.Inject;

import dagger.android.support.DaggerAppCompatActivity;

public class AuthenticationActivity extends DaggerAppCompatActivity
        implements WelcomeContract.onWelcomeLoginClickListener,
        WelcomeContract.onWelcomeSignUpClickListener,
        LoginContract.View.onLoginButtonClickListener,
        LoginContract.View.onSignupClickListener,
        SignUpContract.View.onLoginClickListener,
        SignUpContract.View.onSignupButtonClickListener, GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = AuthenticationActivity.class.getSimpleName();

    @Inject
    WelcomeFragment mWelcomeFragmentProvider;

    @Inject
    LoginFragment mLoginFragmentProvider;

    @Inject
    SignUpFragment mSignUpFragmentProvider;
    private GoogleApiClient mGoogleApiClient;

    // Firebase
    @Inject
    FirebaseAuth mFirebaseAuth;

    FirebaseUser mFirebaseUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);


        WelcomeFragment welcomeFragment = (WelcomeFragment) getSupportFragmentManager()
                .findFragmentById(R.id.authenticationActivity_fragment);

        if(welcomeFragment == null){

            welcomeFragment = mWelcomeFragmentProvider;

            Log.d("AuthActivity", mWelcomeFragmentProvider.toString());

            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),
                    welcomeFragment, R.id.authenticationActivity_fragment);

        }

        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions
                .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
                .build();


        // Load previously saved state, if available.
        if (savedInstanceState != null) {
//            TasksFilterType currentFiltering =
//                    (TasksFilterType) savedInstanceState.getSerializable(CURRENT_FILTERING_KEY);
//            mTasksPresenter.setFiltering(currentFiltering);
        }

    }


    @Override
    public void onWelcomeSignUpButtonClicked() {
        SignUpFragment signUpFragment = mSignUpFragmentProvider;

        ActivityUtils.replaceFragmentInActivity(getSupportFragmentManager(),
                signUpFragment, R.id.authenticationActivity_fragment);
    }

    @Override
    public void onWelcomeLoginButtonClicked() {

        LoginFragment loginFragment = mLoginFragmentProvider;

        ActivityUtils.replaceFragmentInActivity(getSupportFragmentManager(),
                loginFragment, R.id.authenticationActivity_fragment);

    }

    @Override
    public void onLoginButtonClicked() {

    }

    @Override
    public void onSignupTextViewClicked() {
        onWelcomeSignUpButtonClicked();
    }

    @Override
    public void onSignupButtonClicked() {

    }

    @Override
    public void onLoginTextViewClicked() {
        onWelcomeLoginButtonClicked();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }

    public GoogleApiClient getmGoogleApiClient() {
        return mGoogleApiClient;
    }

    public void setmGoogleApiClient(GoogleApiClient mGoogleApiClient) {
        this.mGoogleApiClient = mGoogleApiClient;
    }

    @Override
    protected void onStart() {
        super.onStart();

        // Check if user is signed in.
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseUser = mFirebaseAuth.getCurrentUser();

        if (mFirebaseUser != null) {
            //Not signed in launch the Sign In activity
            startActivity(new Intent(this, MyZoneActivity.class));
            finish();
        }
    }
}

WelcomeFragment.java :

package com.nopeia.fitassistant.ui.authentication.welcome;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.nopeia.fitassistant.R;
import com.nopeia.fitassistant.ui.authentication.login.LoginContract;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dagger.android.support.DaggerFragment;


public class WelcomeFragment extends DaggerFragment {


    @BindView(R.id.welcome_activity_login_ButtonView)
    Button mLoginButtonView;

    @BindView(R.id.welcome_activity_signup_ButtonView)
    Button mSignUpButtonView;

    private WelcomeContract.onWelcomeSignUpClickListener mSignupCallback;
    private WelcomeContract.onWelcomeLoginClickListener mLoginCallback;


    @Inject
    public WelcomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
        ButterKnife.bind(this, rootView);

        mLoginButtonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLoginCallback.onWelcomeLoginButtonClicked();
            }
        });

        mSignUpButtonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSignupCallback.onWelcomeSignUpButtonClicked();
            }
        });

        return rootView;
    }


    @Override
    public void onAttach(Context context) {

        try {
            mSignupCallback = (WelcomeContract.onWelcomeSignUpClickListener) context;
        } catch (ClassCastException e){
            throw new ClassCastException(context.toString()
                    + " must implement onSignupButtonClickListener"
            );
        }

        // Get login callback activity
        try {
            mLoginCallback = (WelcomeContract.onWelcomeLoginClickListener) context;
        } catch (ClassCastException e){
            throw new ClassCastException(context.toString()
                    + " must implement onLoginClickListener"
            );
        }

        super.onAttach(context);



    }

    @Override
    public void onDetach() {

        mSignupCallback = null;
        mLoginCallback = null;

        super.onDetach();

    }

}

ActivityUtil.java:

package com.nopeia.fitassistant.util;

import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.nopeia.fitassistant.R;

import static android.support.v4.util.Preconditions.checkNotNull;

/**
 * Created by Pujolsluis on 12/7/2017.
 */

public class ActivityUtils {


    @SuppressLint("RestrictedApi")
    public static void addFragmentToActivity (@NonNull FragmentManager fragmentManager,
                                              @NonNull Fragment fragment, int frameId) {
        checkNotNull(fragmentManager);
        checkNotNull(fragment);
        String backStateName =  fragment.getClass().getName();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(frameId, fragment, backStateName);
        transaction.commit();
    }

    public static void replaceFragmentInActivity(@NonNull FragmentManager fragmentManager,
                                                 @NonNull Fragment fragment, int frameId){

        //Avoid Fragments stacking up in the backstack if they already exist in it
        String backStateName =  fragment.getClass().getName();

        boolean fragmentPopped = fragmentManager.popBackStackImmediate (backStateName, 0);

        if (!fragmentPopped){ //fragment not in back stack, create it.

            FragmentTransaction transaction = fragmentManager.beginTransaction();

            // Replace fragment, with fade in and fadeout animation
            // and add transaction to backstack to allow the user to undo
            // the action he just did and recover the last fragment state
            transaction.setCustomAnimations(
                    android.R.anim.slide_in_left,
                    android.R.anim.slide_out_right,
                    android.R.anim.slide_in_left,
                    android.R.anim.slide_out_right
            );
            transaction.replace(frameId, fragment);
            transaction.addToBackStack(backStateName);

            transaction.commit();
        }

    }

}

Firebase change “DisplayName” only if password is correct

Im working on my firebase application and I need some help with the logic because currently, it is not working as intended.

Im trying to make it so that a logged in user is only able to change their name if they type in the correct password.

With my current code it changes the name despite of the toast message that the entered password was in-correct.

/**
     * Update Name Only
     */
    private void updateDisplayNameOnly(){

        showProgress();

        AuthCredential credential = EmailAuthProvider
                .getCredential(FirebaseAuth.getInstance().getCurrentUser().getEmail(), mConfirm.getText().toString());

        FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential)
                .addOnCompleteListener(new OnCompleteListener<Void>()
                {
                    @Override
                    public void onComplete(@NonNull Task<Void> task)
                    {
                        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                        UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
                                .setDisplayName(mName.getText().toString())
                                //.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
                                .build();

                        user.updateProfile(profileUpdate);

                        if (task.isSuccessful())
                        {
                            Log.d(TAG, "onComplete: User Profile updated");
                            hideProgress();

                            Toast.makeText(getActivity(), "NAME IS UPDATED XD XD XD", Toast.LENGTH_SHORT).show();

                            // RESTART APP FOR CHANGES
                        }

                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        hideProgress();
                        Toast.makeText(getActivity(), "NAME WAS NOT UPDATED 2", Toast.LENGTH_SHORT).show();
                    }
                });

    }

Please help me with this

PrintStream Only Printing out the Last Line of Input File

I have this code

public class program {
    public static void main(String[] args) {
        try {
            String filePath = (args[0]);
            String strLine;

            BufferedReader br = new BufferedReader(new FileReader(filePath));

            //Read File Line By Line and Print the content on the console
            while ((strLine = br.readLine()) != null) {
            //System.out.println (strLine);
            PrintStream out = new PrintStream(new FileOutputStream( //printing output to user specified text file (command line argument: outputfile)
                    args[1]+".txt"));   
                out.print(strLine);
            }
            //close the streams
            br.close();
            }
            catch(IOException e){
            System.err.println("An IOException was caught :"+e.getMessage());
            }

    }
}

If I invoke this program from the command line using java program input.txt output

and if input file contents were this:
hello
hi
bye

the output file would print this:
bye

It is only printing the last line of the output.

if instead of:

  PrintStream out = new PrintStream(new FileOutputStream( //printing output to user specified text file (command line argument: outputfile)
                args[1]+".txt"));   
            out.print(strLine);

I only had

System.out.println (strLine);

within the while loop, then it would correctly print each line from the input file to the console.

Why when I try to print it to another file it only prints the last line?

NullPointerException when using getSupportActionBar

I am trying to implement a simple navigation drawer in my Android app but I am not able to solve a certain bug.

Attempting to run an app throws a NullPointerException:

Process: com.emertonalex.whiskynotes04, PID: 22225
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emertonalex.whiskynotes04/com.emertonalex.whiskynotes04.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                  at com.emertonalex.whiskynotes04.MainActivity.setupToolbar(MainActivity.java:320)
                  at com.emertonalex.whiskynotes04.MainActivity.onCreate(MainActivity.java:97)
                  at android.app.Activity.performCreate(Activity.java:6999)
                  at android.app.Activity.performCreate(Activity.java:6990)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                  at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                  at android.os.Handler.dispatchMessage(Handler.java:106) 
                  at android.os.Looper.loop(Looper.java:164) 
                  at android.app.ActivityThread.main(ActivityThread.java:6494) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

As far as I see it the getSupportActionBar() function call that messes stuff up. I tried covering the call with the “assert” in setupToolbar() and it seems like it passes that stage and fails at the

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

The pieces of code themselves that call the getSupportActionBar() are these:

In MainActivity

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.add_notes);
   ...
   setupToolbar();

   getSupportActionBar().setDisplayHomeAsUpEnabled(false);
   getSupportActionBar().setHomeButtonEnabled(true);
   ...
} 

And

void setupToolbar(){
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

I am new to Android/Java dev and would be very appreciative of any help.
Also, it would be great if you tell me why this error appears, to begin with, so I can avoid it in the future.

Thank you

Using Robot to move mouse down when pressed Java [on hold]

I’m trying to make a program where when I press and hold the mouse, it moves the cursor down. It’s going to be for a video game. I’ve been trying to find some code to go off of, but I’m a little confused.

So far I have this, Not too sure where I am going wrong, but I just learned about using Mouse Events, so I am sure i’m making a stupid mistake.

If anybody could take a look and help me out that would be great.

import java.awt.Robot;
import java.awt.*;
import java.awt.event.*;

public class MoveMouse{

 private static final long FIFTY_MILLISECONDS = 50;

 addMouseListener(new MouseAdapter() {
     public void mousePressed(MouseEvent me) {
         // Get x,y and store them
        int pY;
        int pX;
        final int FIFTY_MILISECONDS = 50;
        pX = me.getX();
        pY = me.getY();
     }
})
 Robot robot = new Robot();

 public void mousePressed(MouseEvent me) {


     //Should move the mouse's Y Coordinate 15px lower.
     //if its still pressed fifty milliseconds later do it again.


        robot.mouseMoverandom.nextInt(pY - 15);
        Thread.sleep(FIFTY_MILLISECONDS);
    }   

 }

Inconvertible types error in Android

I want to do menus.add(menuTemp); but it shows Inconvertible types error. I tried menus.add((Restaurant.Menu) menuTemp), this didn’t work. Any suggestion?

ArrayList<String> menuTemp = new ArrayList<>();

List<List<Restaurant.Menu>> menus = new ArrayList<>();

Also, It shows this detail on this code.
add (java.util.List<oz.ncclife.model.Restaurant.Menu>)
to (java.util.ArrayList<java.lang.String>)

A part of project may help

ArrayList<Object> objPhones = tinydb.getListObject("restPhones",Object.class);
ArrayList<Object> objMenus = tinydb.getListObject("restMenus",Object.class);

ArrayList<String> phoneTemp = new ArrayList<String>();
ArrayList<String> menuTemp = new ArrayList<>();

for(int i = 0; i < objPhones.size(); i++)
{
            phoneTemp.add(objPhones.get(i).toString());
            menuTemp.add(objMenus.get(i).toString());
}
phones.add(phoneTemp);
menus.add(menuTemp);

Initializing Firebase Admin in App Engine standard Java

I’m trying to use Firebase Auth in App engine standard Java to verify tokens from Android.

However, when I try to initialize Firebase admin, I get an Exception.

here is the exception:

java.lang.NoSuchMethodError: 
com.google.common.base.Preconditions.checkState
(ZLjava/lang/String;Ljava/lang/Object;)V
at com.google.firebase.FirebaseApp.checkNotDeleted (FirebaseApp.java:352)
at com.google.firebase.FirebaseApp.getOptions (FirebaseApp.java:267)
at com.google.firebase.FirebaseApp$TokenRefresher.<init> (FirebaseApp.java:434)
at com.google.firebase.FirebaseApp$TokenRefresher$Factory.create (FirebaseApp.java:535)
at com.google.firebase.FirebaseApp.<init> (FirebaseApp.java:113)
at com.google.firebase.FirebaseApp.initializeApp (FirebaseApp.java:201)
at com.google.firebase.FirebaseApp.initializeApp (FirebaseApp.java:188)
at com.google.firebase.FirebaseApp.initializeApp (FirebaseApp.java:175)

Most likely, because of conflict in Guava versions

here is my gradle:

dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.60'
    compile 'com.google.appengine.tools:appengine-gcs-client:0.7'
    compile ('com.google.firebase:firebase-admin:5.7.0') {
        exclude group: 'com.google.guava'
    }
    compile 'com.google.guava:guava:23.0'
    compile 'javax.servlet:servlet-api:2.5'
}

Here is the code:

InputStream in = filterConfig.getServletContext()
            .getResourceAsStream("/WEB-INF/PRIVATE_KEY_JSON.json");

FirebaseOptions options = null;
try {
     options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(in))
            .build();
} catch (IOException e) {
    e.printStackTrace();
}
FirebaseApp.initializeApp(options);

Reverse edges to get undirected graph on Java [on hold]

Let’s say you are representing a directed graph with this data structure:

public Map<V,Map<V,Edge<V>>> vertexEdgeMap = new HashMap<>();

{
    a={b=Edge@7852e922, c=Edge@4e25154f}, 
    b={c=Edge@70dea4e, d=Edge@5c647e05},
    c={d=Edge@33909752}
}

node ‘a’ is linked to node ‘b’ by the edge @7852e922

node ‘a’ is linked to node ‘c’ by the edge @4e25154f

node ‘b’ is linked to node ‘c’ by the edge @70dea4e

node ‘b’ is linked to node ‘d’ by the edge @5c647e05

node ‘c’ is linked to node ‘d’ by the edge @33909752

How can i reverse the edges to get this exact output ?

{
    a={b=Edge@7852e922, c=Edge@4e25154f}, 
    b={c=Edge@70dea4e, d=Edge@5c647e05, a=Edge@7852e922},
    c={d=Edge@33909752, a=Edge@4e25154f, b=Edge@70dea4e}
}

The code i’m using to generate the edges and the graph is:

Edge.java

public class Edge<V> {

    public final V from;
    public final V to;
    public final double weight;


    public Edge(V from, V to, double weight) {
        this.from = from;
        this.to = to;
        this.weight = weight;
        if (Double.isNaN(weight)) {
            throw new IllegalArgumentException("The weight is NaN.");
        }
        if (weight < 0.0) {
            throw new IllegalArgumentException("The weight is negative.");
        }
    }

}

Graph.java

import java.util.*;

import static java.lang.String.*;

public class Graph<V> {

    public Map<V,Map<V,Edge<V>>> vertexEdgeMap = new HashMap<>();

    @SafeVarargs
    public Graph(Edge<V> ... edges) {
        for (Edge<V> edge : edges) {
            addEdge(edge);
        }
    }


    private void addEdge(Edge<V> edge) {
        vertexEdgeMap.putIfAbsent(edge.from, new HashMap<>());
        Map<V, Edge<V>> fromMap = vertexEdgeMap.get(edge.from);
        if(fromMap.containsKey(edge.to)) {
            throw new IllegalArgumentException(format("Edge between %s and %s was added twice", edge.from, edge.to));
        }
        fromMap.put(edge.to, edge);

    }


    public Edge<V> get(V from, V to) {
        return vertexEdgeMap.get(from).get(to);
    }

    public Collection<Edge<V>> get(V from) {
return vertexEdgeMap.getOrDefault(from, Collections.emptyMap()).values();

    }

}

Execution.java

public class Execution {

    public static void main(String[] args) {
        execution();
    }

    private static <V> void execution() {



        Graph<Character> graph = new Graph<>(
                new Edge<>('a', 'c', 3.0),
                new Edge<>('a', 'b', 5.0),

                new Edge<>('b', 'c', 2.0),

                new Edge<>('b', 'd', 1.0),

                new Edge<>('c', 'd', 3.0)

        );
  }
}

Can I change the role after the authentication is successful?

I successfully passed Github authentication with Spring Security OAuth2. However, the user role obtained through Github is USER_ROLE.

So I was wondering if I could modify the corresponding role by judging Github user information obtained after the authorization was successful in order to control the user’s permissions.

For example, getPrincipal () to get a unique “name”. Then modify the role by “name” (such as “ADMIN”). Finally, use @PreAuthorize (“hasRole (‘ROLE_ADMIN’)”) to control permissions.

Or are there any other better solutions? I want to integrate Github’s OAuth2 authorization and role-based rights management in this application.

Using Robot to move mouse down when pressed Java

I’m trying to make a program where when I press and hold the mouse, it moves the cursor down. It’s going to be for a video game. I’ve been trying to find some code to go off of, but I’m a little confused.

So far I have this, Not too sure where I am going wrong, but I just learned about using Mouse Events, so I am sure i’m making a stupid mistake.

If anybody could take a look and help me out that would be great.

import java.awt.Robot;
import java.awt.*;
import java.awt.event.*;

public class MoveMouse{

 private static final long FIFTY_MILLISECONDS = 50;

 addMouseListener(new MouseAdapter() {
     public void mousePressed(MouseEvent me) {
         // Get x,y and store them
        int pY;
        int pX;
        final int FIFTY_MILISECONDS = 50;
        pX = me.getX();
        pY = me.getY();
     }
})
 Robot robot = new Robot();

 public void mousePressed(MouseEvent me) {


     //Should move the mouse's Y Coordinate 15px lower.
     //if its still pressed fifty milliseconds later do it again.


        robot.mouseMoverandom.nextInt(pY - 15);
        Thread.sleep(FIFTY_MILLISECONDS);
    }   

 }