findViewById()从片段中返回null - Android

时间:2015-01-09 16:36:49

标签: java android android-fragments nullpointerexception findviewbyid

我尝试从MainActivity更新我的应用中的进度条,但它不允许我引用片段内的任何内容。如果我通过使用它来引用片段,但片段会在所有内容之下呈现(因为我的应用程序会在单个活动中切换片段)。由于进度条的原因,我尝试过的任何内容都会在运行时返回NullPointerException。

My Fragment的.java文件:



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));
    }
}




我尝试了各种不同的解决方案,看了一下,几乎到处都看到人们说要给片段充气,但它却被夸大了,我不知道为什么它不是。工作...任何帮助将不胜感激!我还是Java的新手! :P我确定我一直是个白痴,我不能看到我做过的......

P.S。我试图从布局中获取的所有内容都存在于XML文件中,所以......不是这样! :P

这是我的fragment for fragment_server_status

的XML



<?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>
&#13;
&#13;
&#13;

我按照建议添加OnViewCreated,运行它并且...... :(仍然是一个NullpointerException。玩得开心:D

&#13;
&#13;
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)
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

似乎在片段膨胀之前调用refresh。这意味着onCreateView尚未被调用,cpuPercentage仍为空。

如果您确实需要从片段外部调用refresh,请添加检查以查看是否已设置cpuPercentage

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

以同样的方式将检查添加到每个其他字段,即ramPercentage和tempValue。

注意:我认为这些字段不应该是静态的。