安卓下拉框为空。

4
这是我的主要活动。即使已经初始化,我的spinner仍为null。每当访问任何布局元素时,我的应用程序都会崩溃,但我却无法弄清原因。我已经花了相当长的时间在这上面,查阅了很多在线帖子以寻求解决方案,并尝试了许多修复方法,但迄今为止都没有起作用。有什么想法吗?
另外,请忽略日期创建/排序代码。它非常混乱,我已经有了更整洁的方式来处理它,但在解决此部分问题之前不会实施。
注意:我的布局中所有id都是正确的,我非常确定这不是问题所在。 public class RADIO_Live extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;

ViewPager mViewPager;
View fragviewLive;
View fragviewPod;

private int mYear, mMonth, mDay, cYear, cMonth, cDay;
private TextView mCurrentDate;
private TextView mSelectedDate;
private TextView TextCurrentTime;
private TextView TextTotalTime;

boolean firstRUN = true;

SeekBar Podseekbar;
int myProgress = 0;
int podMax = 0;
int CurrentPosition = 0;

boolean playerPODon = false;        // variable to keep track if live stream player and podcast player is on or off and if podacast player is paused
boolean playerPODon1st = true;

String mMonthName, cMonthName, cMonthFullName;
String podFileTest, podPlayName, SelectedHour, SelectedDate = null;
String showdate, HourShowText = null;

String[] podDates = new String[14];
String[] podDatesName = new String[14];
int testDay = 0;
int dayOfWeek;

private final Handler UIhandler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    //context.startService(serviceIntent);
    startService(new Intent(this, RADIO_Service.class));

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    fragviewPod = getLayoutInflater().inflate(R.layout.podcasts, null);

    // Capture the textview elements
    mCurrentDate = (TextView) fragviewPod.findViewById(R.id.currentdateDisplay);
    mSelectedDate = (TextView) fragviewPod.findViewById(R.id.selecteddateDisplay);

    TextTotalTime = (TextView) fragviewPod.findViewById(R.id.TotalTimeText);
    TextCurrentTime = (TextView) fragviewPod.findViewById(R.id.CurrentTimeText);

    // Retrieve the current date
    Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    IntentFilter filt = new IntentFilter("fromService");
    RADIO_Live.this.registerReceiver(br, filt);

    IntentFilter Podfilt = new IntentFilter("fromServicePod");
    RADIO_Live.this.registerReceiver(PODbr, Podfilt);

    actBroadcast("null", "whatsplaying");

    ArrayList<CharSequence> dateadapterarray = new ArrayList<CharSequence>();

    int ArrayMarker = 0;
    for (int podtest = 1; podtest < 15; podtest++)  {
        MakeDateList(podtest);
        if (dayOfWeek != (1|7)) {
            podFileTest = cMonthName + " " + cDay + ", " + cYear;
            podDatesName[ArrayMarker] = podFileTest;
            String cYearTemp = cYear + "";
            String cMonthTemp = cMonth + "";
            if (cMonth >= 10) {
            } else {
                cMonthTemp = cMonthTemp.replace("0", "");
                cMonthTemp = "0" + cMonthTemp;
            }

            if (cDay > 9)   {
                podDates[ArrayMarker] = (cMonthTemp + "" + cDay + "" + cYearTemp.replace("20", ""));
            }
            if (cDay <= 9)  {
                podDates[ArrayMarker] = (cMonthTemp + "" + "0" + cDay + "" + cYearTemp.replace("20", ""));
            }
            ArrayMarker++;

        }
        if (dayOfWeek == (1|7) && (ArrayMarker > 0))    {
            ArrayMarker--;
        }
    }

    for (int buildtext = 0; buildtext < 14; buildtext++) {
        dateadapterarray.add(podDatesName[buildtext]);
    }

    fragviewPod = getLayoutInflater().inflate(R.layout.podcasts, null);
    Spinner datespinner = (Spinner) fragviewPod.findViewById(R.id.spinnerdate);
    Spinner hourspinner = (Spinner) fragviewPod.findViewById(R.id.spinnerhour);
    //Spinner hourspinner = (Spinner) mViewPager.findViewById(R.id.spinnerhour);

    ArrayAdapter<CharSequence> dateadapter = new ArrayAdapter<CharSequence>(RADIO_Live.this, android.R.layout.simple_spinner_item, dateadapterarray);
    dateadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    ArrayAdapter<CharSequence> houradapter = new ArrayAdapter<CharSequence>(RADIO_Live.this, android.R.layout.simple_spinner_item, R.array.hour_array);
    houradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


    datespinner.setAdapter(dateadapter);
    hourspinner.setAdapter(houradapter);

    // Display the current date under "Today's Date" at the top
    updateCurrentDate();
    datespinner.setOnItemSelectedListener(new DateOnItemSelectedListener());
    hourspinner.setOnItemSelectedListener(new HourOnItemSelectedListener());

    Button livebutton = (Button) fragviewLive.findViewById(R.id.button_streamstartstop);
    //livebutton.setOnClickListener((View.OnClickListener) this);

    Button podplaybutton = (Button)fragviewPod.findViewById(R.id.button_pod_play);
    //podplaybutton.setOnClickListener((View.OnClickListener) this);

}
更新:这里是视图被加载的地方。我尝试将两个视图膨胀到自己的静态LinearLayout中,但也不起作用。

所以在主活动开始时:

static LinearLayout livelayout;
static LinearLayout podlayout;

然后就是代码片段。它实际上是从Android Studio的空默认应用程序中提取的代码,并将我的东西填充其中:

public static class DummySectionFragment extends Fragment {
    public DummySectionFragment() {
    }

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        Bundle args = getArguments();
        int test = args.getInt(ARG_SECTION_NUMBER);

        livelayout = (LinearLayout)inflater.inflate(R.layout.live, null);
        podlayout = (LinearLayout)inflater.inflate(R.layout.podcasts, null);

        inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int resID = 0;
        switch (test) {
            case 1:
                    resID = R.layout.live;
                    break;
            case 2: 
                    resID = R.layout.podcasts;
                    break;
        }
        //textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
        View fragview = inflater.inflate(resID, null);
        return fragview;
    }
}

为了澄清,我有一个main.xml文件,其中包含标题、页面适配器以及live.xml和podcast.xml两个文件。
Main.xml:
<android.support.v4.view.ViewPager         
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RADIO_Live" >

<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip android:id="@+id/pager_title_strip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="#33b5e5"
    android:textColor="#fff"
    android:paddingTop="4dp"
    android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>

Live.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical" >

<LinearLayout android:id="@+id/tab1.1"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_marginTop="15sp"
        android:layout_marginBottom="10sp" android:layout_marginLeft="30sp"
        android:layout_marginRight="30sp" android:textSize="18sp"
        android:text="@string/LiveTabBlurb" />
</LinearLayout>
<Button android:id="@+id/button_streamstartstop"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:layout_marginTop="10sp" android:layout_marginLeft="20sp"
    android:layout_marginRight="20sp" android:textSize="28sp"
    android:textStyle="italic" android:textColor="#FFFFFF" android:text="@string/ListenLiveText" android:onClick="LiveButtonClick" />

<ProgressBar android:layout_gravity="center"
    android:layout_height="100dp" android:layout_width="wrap_content"
    android:id="@+id/liveProgress" android:paddingTop="30dp"
    android:indeterminateBehavior="cycle" android:indeterminate="true"
    android:visibility="gone">
</ProgressBar>

<ProgressBar
    android:id="@+id/liveProgress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="20dp"
    android:visibility="gone" />

</LinearLayout>

Podcasts.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab2" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="#ffffff">

<LinearLayout android:orientation="horizontal" android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <LinearLayout android:orientation="vertical" android:layout_width="160dp"
        android:layout_height="wrap_content">
        <TextView android:id="@+id/currentdateDescription"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:paddingTop="5px" android:text="Today's Date:" />
        <TextView android:id="@+id/currentdateDisplay"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:paddingBottom="5px" android:text="" />
    </LinearLayout>
    <LinearLayout android:orientation="vertical" android:layout_width="160dp"
        android:layout_height="wrap_content">
        <TextView android:id="@+id/selecteddateDescription"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:paddingTop="5px" android:text="Selected Date:" />
        <TextView android:id="@+id/selecteddateDisplay"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:paddingBottom="5px" android:text="None Selected" />
    </LinearLayout>
</LinearLayout>
<LinearLayout android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <Spinner android:id="@+id/spinnerdate" android:layout_width="160dp"
        android:layout_height="wrap_content" android:prompt="@string/date_prompt" />
    <Spinner android:id="@+id/spinnerhour" android:layout_width="160dp"
        android:layout_height="wrap_content" android:prompt="@string/hour_prompt" />
</LinearLayout>
<Button android:id="@+id/button_pod_play"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:layout_marginLeft="20sp" android:layout_marginRight="20sp"
    android:paddingTop="5sp" android:layout_marginTop="10sp"
    android:textSize="28sp" android:textColor="#FFFFFF" android:textStyle="italic"
    android:text="@string/PlayPodText" android:onClick="PodButtonClick"/>
<SeekBar android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:paddingTop="5dp"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_margin="10dp" android:id="@+id/seekBar" android:max="100"
    android:progress="0" />

<LinearLayout android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@+id/CurrentTimeText"
        android:layout_width="60dp" android:layout_height="wrap_content"
        android:paddingTop="5px" android:textSize="18px" android:text="0:00" />
    <ProgressBar android:layout_gravity="center"
        android:layout_height="wrap_content" android:layout_width="fill_parent"
        android:id="@+id/podProgress" android:paddingTop="10px"
        android:indeterminateBehavior="cycle" android:indeterminate="true"
        android:visibility="gone">
    </ProgressBar>
    <TextView android:id="@+id/TotalTimeText"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:paddingTop="5px" android:gravity="right" android:textSize="18px"
        android:text="0:00" />
</LinearLayout>

</LinearLayout> 

稍微解释一下背景。这个应用实际上是百分百工作的,但我使用了一个丑陋的Android 2.0时代的选项卡界面,并希望更新为一个漂亮的Holo界面和页面视图适配器。由于以前从未做过这样的事情,我试着去做,结果出现了这些问题。
更新:我已经让一些东西工作了(有点)。在调试时,我的两个下拉列表不再是null了,至少按照调试器的说法是这样。但是每当活动访问任何布局对象时,应用程序仍然会崩溃。如果我尝试设置任何文本视图或下拉列表框,似乎要么崩溃,要么只是不更新内容。
片段代码:
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        //Fragment fragment = new DummySectionFragment();

        Fragment fragment;
        Bundle args = new Bundle();
        switch(i){
            case 0:
                fragment = new fragLive();
                args.putInt(fragLive.ARG_SECTION_NUMBER, i + 1);
                break;
            case 1:
                fragment = new fragPod();
                args.putInt(fragPod.ARG_SECTION_NUMBER, i + 1);
                break;
            default:
                fragment = new fragLive();
                args.putInt(fragLive.ARG_SECTION_NUMBER, i + 1);
                break;
        }

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0: return getString(R.string.title_section1).toUpperCase();
            case 1: return getString(R.string.title_section2).toUpperCase();
        }
        return null;
    }
}

/**
 * Two classes for the two layout fragments
 */
public class fragLive extends Fragment {
    public fragLive() {
    }

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        Bundle args = getArguments();
        int test = args.getInt(ARG_SECTION_NUMBER);

        inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
        fragviewLive = inflater.inflate(R.layout.live, null);
        return fragviewLive;
    }
}

public class fragPod extends Fragment {
    public fragPod() {
    }

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        Bundle args = getArguments();
        int test = args.getInt(ARG_SECTION_NUMBER);

        inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
        fragviewPod = inflater.inflate(R.layout.podcasts, null);
        return fragviewPod;
    }
}

请发布XML数据。 - Cheborra
请发布您的main.xml文件,您的下拉菜单未初始化,因此出现了NPE错误。 - Raghunandan
发布。是的,这些项实际上并不在main.xml中。这只是一种情况,就像它在你面前一样,但你却看不见它。现在我尝试将布局放入静态对象中,但似乎也不起作用。有什么建议吗? - Chris
SectionsPagerAdapter 是你的类,对吧?看一下那段代码会有帮助。 - invertigo
@invertigo,我更新了我的帖子,并分享了我目前的工作进展。你能再帮我看一下吗?我花了太多时间在这个肯定很简单的事情上了。 - Chris
3个回答

3

首先检查你的main.xml布局中是否有R.id.spinnerdate。
如果是这种情况,请尝试以下操作:

由于你正在使用FragmentActivity,所以需要先填充你的布局。

 private View myView;

 .....

myView = getLayoutInflater().inflate(R.layout.main, null);

并将日期微调器的引用更改为:

Spinner datespinner = (Spinner) myView.findViewById(R.id.spinnerdate);

你说得对。我参考的项目实际上并不在main.xml中,而是在其中一个片段布局中。请查看我的更新帖子以获取所有细节。 - Chris

2
您需要在片段的视图上调用findViewById()
Spinner datespinner = (Spinner) fragmentThatContainsSpinner.getView().findViewById(R.id.spinnerdate);

我不知道如何做那个。我不知道"fragmentThatContainsSpinner"应该是什么或者如何引用它。 我唯一看到fragment视图的地方是: View fragview = inflater.inflate(resID, null); return fragview; 但我不知道如何从onCreate中调用它。 - Chris
你真正需要做的是看看你如何使用你的片段。你可能应该有两个片段类,播客和直播,并在你的主活动中管理它们。然后在各自的片段中,你将能够引用每个布局中的视图。 - invertigo

1
问题在于上下文化,这是一个有点奇怪的问题。上下文问题应该被消除,对象应该无需任何上下文或作用域问题即可使用。但在等待此类更新之前,我们可以使用以下解决方案。
例如,当您在片段中的按钮上设置单击监听器时...
示例(空)片段代码:
MyButton.setOnClickListener(new View.OnClickListener(){

  @Override 
  public void onClick(View MyClickViewer) {

    //here the spinner is null?
    Spinner MySpinner = null; 

    //it is so result is null...
    MyClickViewer.findViewById(R.id.a_spinner);

  }

}
  • MyClickViewer存在于Click视图的上下文中。
  • MySpinner存在于根视图的上下文中。

示例(非空)Spinner检索:

//not null anymore...
Spinner MySpinner = 
  (Spinner)MyClickViewer.getRootView().findViewById(R.id.a_spinner);

方法 getRootView() 允许您创建“fragment.xml”文件,而无需在任何“main.xml”文件中重新定义对象。此外,由于现在已被引用而不是空值,因此您可以从Spinner获取任何值。 示例(非空)Spinner位置:
MySpinner.getSelectedItemPosition()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接