java – How to use all methods and get/update values from activity inside a fragment-ThrowExceptions

Exception or error:

before I had an IntroductionActivity which looked like this (worked perfectly):

public class IntroductionActivity extends AppCompatActivity implements FirebaseUserProfile.OnRegistrationCompleteListener{

    private FirebaseUserProfile the_firebase_profile_class = new FirebaseUserProfile(this);

    private Boolean connectedWithWifi, connectedWith4G;
    private TextView networkInformationStatus, usernameTextField;


    private Socket mSocket;
    private Handler mHandler;

    public static final String SHARED_PREFS_2 = "sharedPrefs_IntroMessage";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_introduction);
        this.mHandler = new Handler();
        RunInBackground.run();

        networkInformationStatus = findViewById(R.id.networkStatusID);
        usernameTextField = findViewById(R.id.usernameID);

        SharedPreferences retreive_uid = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
        String uid_of_user = retreive_uid.getString("UID_OF_USER","the_uid");





        establishConnection();
        the_firebase_profile_class.getPersonalUserDetails();





        WebSocketClass the_websocket_class = (WebSocketClass) getApplication();
        mSocket = the_websocket_class.getSocket();
        mSocket.connect();




        Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
        //webSocketBtn.setVisibility(View.INVISIBLE);
        webSocketBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                saveData();


            }
        });



    private void establishConnection(){
        try {

            checkNetworkConnection();
        }
        catch(Exception e) {

        }

    }

    private void checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            connectedWithWifi = networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
            connectedWith4G = networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;

            if(connectedWithWifi){
                networkInformationStatus.setText("Wifi is connected!");
                networkInformationStatus.setTextColor(Color.GREEN);
                Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
                webSocketBtn.setVisibility(View.VISIBLE);
                //the_firebase_userclass.getUserWorkOutProfile();
                //the_firebase_userclass.getPersonalUserDetails();



            } else if(connectedWith4G){
                networkInformationStatus.setText("Connected with 4G!");
                networkInformationStatus.setTextColor(Color.GREEN);
                Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
                webSocketBtn.setVisibility(View.VISIBLE);
                //the_firebase_userclass.getUserWorkOutProfile();
                //the_firebase_userclass.getPersonalUserDetails();




            }

        } else{

            networkInformationStatus.setText("Not connected to internet!");
            networkInformationStatus.setTextColor(Color.RED);
            Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
            webSocketBtn.setVisibility(View.GONE);

        }


    }

    private final Runnable RunInBackground = new Runnable()
    {
        public void run()

        {
            IntroductionActivity.this.mHandler.postDelayed(RunInBackground,200);
            establishConnection();
        }

    };

    public void saveData(){
        //String the_status_of_introMessage = the_firebase_userclass.getStatusOfIntroMessage();
        Log.d("tag", "WHAT IS BOOLEAN HERE? " + the_firebase_profile_class.getUserHasSeenTheIntroMessage());
        Boolean the_status_of_introMessage = Boolean.valueOf(the_firebase_profile_class.getUserHasSeenTheIntroMessage());
        SharedPreferences sharedPreferences2 = getSharedPreferences(SHARED_PREFS_2, MODE_PRIVATE);
        SharedPreferences.Editor editor2 = sharedPreferences2.edit();

        editor2.putBoolean("INTRO_MESSAGE_USER", the_status_of_introMessage);
        editor2.apply();
        Intent takeMeToTheWebsocketActivity = new Intent(getApplicationContext(), WebSocketActivity.class);
        startActivity(takeMeToTheWebsocketActivity);

    }

    private void showUserDetails() {

        usernameTextField.setText("Velkommen " + the_firebase_profile_class.getUserName() + "!");
        usernameTextField.setTextColor(Color.BLUE);


    }


    @Override
    public void onRegistrationComplete(boolean success) {
        if(!success) {
            Toast.makeText(this, "An error occured :(", Toast.LENGTH_SHORT).show();

        }
        if(success){
            //Toast.makeText(this, "User-updated", Toast.LENGTH_SHORT).show();

            showUserDetails();

        }

    }


}

As soon as I come to this activity, it used to update me to show what my connection status is and worked pretty good.

However, I use the same activity, but now I also have fragments included. What i want now is a fragment to use the functions and values from the same activity to show the connection status on that particular fragment.

This is how my IntroductionActivity looks now:

public class IntroductionActivity extends AppCompatActivity implements FirebaseUserProfile.OnRegistrationCompleteListener{

    public FirebaseUserProfile the_firebase_profile_class = new FirebaseUserProfile(this);

    public Boolean connectedWithWifi, connectedWith4G;
    public TextView networkInformationStatus, usernameTextField;


    public Socket mSocket;
    public Handler mHandler;

    public static final String SHARED_PREFS_2 = "sharedPrefs_IntroMessage";

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

        this.mHandler = new Handler();
        RunInBackground.run();

        networkInformationStatus = findViewById(R.id.networkStatusID);
        //usernameTextField = findViewById(R.id.usernameID);

        SharedPreferences retreive_uid = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
        String uid_of_user = retreive_uid.getString("UID_OF_USER", "the_uid");


        establishConnection();
        the_firebase_profile_class.getPersonalUserDetails();


        WebSocketClass the_websocket_class = (WebSocketClass) getApplication();
        mSocket = the_websocket_class.getSocket();
        mSocket.connect();

        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        //I added this if statement to keep the selected fragment when rotating the device
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new InstillingerFragment()).commit();
        }
    }

    public BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.nav_instillinger:
                            selectedFragment = new InstillingerFragment();
                            break;

                        case R.id.nav_wifi:
                            selectedFragment = new WifiFragment();
                            break;
                        case R.id.nav_trening:
                            selectedFragment = new TreningFragment();
                            break;
                        case R.id.nav_trenings_plan:
                            selectedFragment = new TreningsPlanFragment();
                            break;


                    }

                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            selectedFragment).commit();

                    return true;
                }
            };

    public void establishConnection() {
        try {

            checkNetworkConnection();
        } catch (Exception e) {

        }

    }

    public void checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            connectedWithWifi = networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
            connectedWith4G = networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;

            if (connectedWithWifi) {
                networkInformationStatus.setText("Wifi is connected!");
                networkInformationStatus.setTextColor(Color.GREEN);
                //Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
                //webSocketBtn.setVisibility(View.VISIBLE);
                //the_firebase_userclass.getUserWorkOutProfile();
                //the_firebase_userclass.getPersonalUserDetails();


            } else if (connectedWith4G) {
                networkInformationStatus.setText("Connected with 4G!");
                networkInformationStatus.setTextColor(Color.GREEN);
                //Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
                //webSocketBtn.setVisibility(View.VISIBLE);
                //the_firebase_userclass.getUserWorkOutProfile();
                //the_firebase_userclass.getPersonalUserDetails();


            }

        } else {

            networkInformationStatus.setText("Not connected to internet!");
            networkInformationStatus.setTextColor(Color.RED);
            //Button webSocketBtn = (Button) findViewById(R.id.webSocketActivityBtn);
            //webSocketBtn.setVisibility(View.GONE);

        }



    }


    public final Runnable RunInBackground = new Runnable() {
        public void run() {
            IntroductionActivity.this.mHandler.postDelayed(RunInBackground, 200);
            establishConnection();
        }

    };

    public void saveData() {
        //String the_status_of_introMessage = the_firebase_userclass.getStatusOfIntroMessage();
        Log.d("tag", "WHAT IS BOOLEAN HERE? " + the_firebase_profile_class.getUserHasSeenTheIntroMessage());
        Boolean the_status_of_introMessage = Boolean.valueOf(the_firebase_profile_class.getUserHasSeenTheIntroMessage());
        SharedPreferences sharedPreferences2 = getSharedPreferences(SHARED_PREFS_2, MODE_PRIVATE);
        SharedPreferences.Editor editor2 = sharedPreferences2.edit();

        editor2.putBoolean("INTRO_MESSAGE_USER", the_status_of_introMessage);
        editor2.apply();
        Intent takeMeToTheWebsocketActivity = new Intent(getApplicationContext(), WebSocketActivity.class);
        startActivity(takeMeToTheWebsocketActivity);

    }

    public void showUserDetails() {

        usernameTextField.setText("Velkommen " + the_firebase_profile_class.getUserName() + "!");
        usernameTextField.setTextColor(Color.BLUE);


    }


    @Override
    public void onRegistrationComplete(boolean success) {
        if(!success) {
            Toast.makeText(this, "An error occured :(", Toast.LENGTH_SHORT).show();

        }
        if(success){
            //Toast.makeText(this, "User-updated", Toast.LENGTH_SHORT).show();

            //showUserDetails();

        }

    }


}

And this is how my WifiFragment looks:

public class WifiFragment extends Fragment {


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {



        getActivity().findViewById(R.id.networkStatusID);  //does not update at all!
        return inflater.inflate(R.layout.fragment_wifi, container, false);


    }
}

I managed to get the networkStatusID from activity_main.layout on the fragment, but the status of the network connection is not shown..

Could someone plz help me?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *