findViewById() Returns null from within a fragment - Android

Adam Price

I'm trying to update progress bars in my app from MainActivity, however it does not let me reference anything that's inside the fragments. If I reference the fragment by using It works but the fragment renders underneath everything (As my app switches fragments out inside a single activity). Anything I've tried returns a NullPointerException on runtime due to the progress bars.

My Fragment's .java file:

package com.example.adam.slypanel;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import java.util.Random;

/**
 * Created by root on 02/10/14.
 */
public class ServerStatusFragment extends Fragment{

    public static ProgressBar cpuPercentage;
    public static ProgressBar ramPercentage;
    public static ProgressBar tempValue;

    public ServerStatusFragment() {

    }

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

        View ServerStatusView = inflater.inflate(R.layout.fragment_server_status, container, false);
        //Right here! D:
        cpuPercentage = (ProgressBar) ServerStatusView.findViewById(R.id.cpuUsageBar);
        ramPercentage = (ProgressBar) ServerStatusView.findViewById(R.id.ramUsageBar);
        tempValue = (ProgressBar) ServerStatusView.findViewById(R.id.tempBar);
        
        return (ServerStatusView);
    }

    //For testing -- Replace when needed
    public static int randInt(int min, int max) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

    public void refresh() {
        cpuPercentage.setProgress(randInt(0, 100));
        ramPercentage.setProgress(randInt(0, 100));
        tempValue.setProgress(randInt(20, 100));
    }
}

I've tried various different solutions, Looked around for a bit and pretty much everywhere I've seen people saying to inflate the fragment, yet it is inflated and I have no idea why it isn't working... Any help will be much appreciated! I'm still a newbie to Java! :P I'm sure I've been an idiot with it and i just can't see what I've done...

P.s. Everything I'm trying to get from the layout is present in the XML file so... It's not that! :P

Here's my XML for fragment_server_status

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/Server_Status_Fragment"
    android:weightSum="1">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="CPU Usage: "
            android:id="@+id/cpuUsageLabel"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="20dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="RAM Usage: "
            android:id="@+id/ramUsageLabel"
            android:layout_toEndOf="@+id/tempLabel"
            android:layout_below="@+id/cpuUsageBar"
            android:layout_alignLeft="@+id/cpuUsageBar"
            android:layout_alignStart="@+id/cpuUsageBar"
            android:layout_marginTop="45dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Temperature"
            android:id="@+id/tempLabel"
            android:layout_below="@+id/ramUsageBar"
            android:layout_alignRight="@+id/cpuUsageLabel"
            android:layout_alignEnd="@+id/cpuUsageLabel"
            android:layout_marginTop="52dp" />

        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="wrap_content"
            android:layout_height="25dp"
            android:id="@+id/cpuUsageBar"
            android:max="100"
            android:progress="25"
            android:indeterminate="false"
            android:layout_marginTop="40dp"
            android:layout_below="@+id/cpuUsageLabel"
            android:layout_alignLeft="@+id/cpuUsageLabel"
            android:layout_alignStart="@+id/cpuUsageLabel" />

        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="120dp"
            android:layout_height="25dp"
            android:id="@+id/ramUsageBar"
            android:max="100"
            android:progress="45"
            android:indeterminate="false"
            android:layout_toEndOf="@+id/tempBar"
            android:layout_centerVertical="true"
            android:layout_alignLeft="@+id/ramUsageLabel"
            android:layout_alignStart="@+id/ramUsageLabel" />

        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="120dp"
            android:layout_height="25dp"
            android:id="@+id/tempBar"
            android:max="100"
            android:progress="60"
            android:indeterminate="false"
            android:layout_marginTop="65dp"
            android:layout_below="@+id/tempLabel"
            android:layout_alignLeft="@+id/tempLabel"
            android:layout_alignStart="@+id/tempLabel" />

    </RelativeLayout>
</LinearLayout>

I added in OnViewCreated as suggested, ran it and... :( Still a NullpointerException. Have fun with the log :D

01-09 16:26:39.571    7746-7746/com.example.adam.slypanel E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.adam.slypanel, PID: 7746
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.adam.slypanel/com.example.adam.slypanel.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:898)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference
            at com.example.adam.slypanel.ServerStatusFragment.refresh(ServerStatusFragment.java:55)
            at com.example.adam.slypanel.MainActivity$1.run(MainActivity.java:77)
            at com.example.adam.slypanel.MainActivity.onSectionAttached(MainActivity.java:107)
            at com.example.adam.slypanel.MainActivity$PlaceholderFragment.onAttach(MainActivity.java:234)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:853)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
            at android.app.BackStackRecord.run(BackStackRecord.java:833)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
            at android.app.Activity.performStart(Activity.java:5948)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:898)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

Simas

It seems that you call refresh before the fragment is inflated. That means onCreateView wasn't yet called and cpuPercentage is still null.

If you really need to call refresh from outside of your fragment, then add checks to see if cpuPercentage is set yet:

if (myFragment.cpuPercentage != null) {
    myFragment.refresh();
}

In the same way add checks to every other field too, i.e. ramPercentage and tempValue.

Note: it looks to me that these fields shouldn't be static.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Android fragment - findViewById returns null

From Dev

findViewById in Fragment returns Null

From Dev

FindViewbyId always returns Null in Fragment

From Dev

findViewById returns null in fragment class

From Dev

FindViewbyId always returns Null in Fragment

From Dev

findViewById returns null in fragment class

From Dev

Calling findViewById in fragment returns null

From Dev

Android - findViewById returns null

From Dev

Android: findViewById returns null

From Dev

Android - Fragment findViewById() always null?

From Dev

findViewById of TextSwitcher returns null after replacing fragment

From Dev

FindViewByID returns null on Fragment Navigation Drawer

From Dev

Android findViewById always returns null

From Dev

android: findViewById returns NULL when accesses from another class

From Dev

android - findViewById NULL under using Fragment

From Dev

Android custom ListView items (findViewById returns null)

From Dev

Android: findViewById returns Null even if is after setContentView

From Dev

Android GridView getChildAt(0).findViewById() returns null

From Dev

Calling findViewById from custom view returns null

From Dev

FindViewByID Fragment Null

From Dev

FindViewByID Fragment Null

From Dev

android getSupportActionBar() returns null in fragment

From Dev

Radio Button findViewById within a Fragment

From Dev

findViewById returns null for WebView

From Dev

findViewById returns null - why?

From Dev

findViewById returns null for WebView

From Dev

findViewById returns null in Listfragment

From Dev

findViewById() function returns null

From Dev

findViewById returns null in AppCompatActivity