简体   繁体   English

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

[英]findViewById() Returns null from within a fragment - Android

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. 我正在尝试从MainActivity更新应用程序中的进度条,但是它不允许我引用片段中的任何内容。 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. 由于进度条,我尝试过的任何操作都会在运行时返回NullPointerException。

My Fragment's .java file: 我的片段的.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)); } } 

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! 我仍然是Java的新手! :P I'm sure I've been an idiot with it and i just can't see what I've done... :P我确定我一直是个白痴,只是看不到我做了什么...

Ps Everything I'm trying to get from the layout is present in the XML file so... It's not that! 附:我想从布局中获取的所有内容都存在于XML文件中,所以……不是那样! :P :P

Here's my XML for fragment_server_status 这是我的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> 

I added in OnViewCreated as suggested, ran it and... :( Still a NullpointerException. Have fun with the log :D 我按照建议添加了OnViewCreated,然后运行它并... :(仍然是NullpointerException。

 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) 

It seems that you call refresh before the fragment is inflated. 似乎您需要在片段膨胀之前调用refresh That means onCreateView wasn't yet called and cpuPercentage is still null. 这意味着尚未调用onCreateView ,并且cpuPercentage仍为null。

If you really need to call refresh from outside of your fragment, then add checks to see if cpuPercentage is set yet: 如果确实需要从片段外部调用refresh ,请添加检查以查看是否设置了cpuPercentage

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

In the same way add checks to every other field too, ie ramPercentage and tempValue. 同样,将检查添加到每个其他字段,即ramPercentage和tempValue。

Note: it looks to me that these fields shouldn't be static. 注意:在我看来,这些字段不应该是静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM