微调器下拉实现从片段调用到新意图

spinner drop down implementation called from fragment to a new intent

我有一个应用程序,我做了一个从片段启动的意图。

但是,当我单击片段中的按钮以启动我制作的客户播放器时,我的activity(这是一个意图)遇到了错误。

错误在这一行:

dropdown.setAdapter(adapter);

这是错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
            at blackstone.software.sunnahboxtvmenu.DuaatRadio.onCreate(DuaatRadio.java:52)

也就是上面说的那一行

我不清楚我是如何对产生错误的下拉列表进行错误编码的。

*** 让我澄清一下:下拉列表中的频道选择是在列出所有频道的数组列表(在 xml 中)中定义的。 代码中的适配器获取列表并应该填充它。但是 - 它似乎没有被填充,因此出现错误。

它在一个独立的应用程序中工作得很好,但是当我试图让它在一个片段产生的意图中工作时(点击按钮),我得到上面列出的错误。

**** 更新:完整代码 ****

这是意图的代码(完整):

import android.annotation.TargetApi;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import static android.R.layout.simple_spinner_dropdown_item;
import static blackstone.software.sunnahboxtvmenu.R.string.app_name;

/**
 * Created by ironmantis7x on 10/26/15.
 */
public class DuaatRadio extends Activity implements AdapterView.OnItemSelectedListener, OnPreparedListener {

    private MediaPlayer mediaPlayer;
    public TextView songName, duration;
    private double timeElapsed = 0, finalTime = 0;
    private int forwardTime = 2000, backwardTime = 2000;
    private Handler durationHandler = new Handler();
    private SeekBar seekbar;
    //String url = "http://radio.miraath.net:7000";
    //String url = new String[]{"http://radio.miraath.net:7000", "http://radio.miraath.net:7010", "http://radio.miraath.net:7020", "http://radio.miraath.net:7030","http://radio.miraath.net:7040", };
    String url;
    TextView radioInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //set the layout of the Activity
        setContentView(R.layout.activity_main);
        Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
        String[] items = new String[]{"Masjid Tawheed Radio", "Masjid Rahmah Radio", "1st Muslim Mosque Radio", "Germantown Masjid Radio", "MPUBS Radio", "UK Dawah Radio"};
        String[] radioDescription = new String[]{"Masjid Tawheed (Atlanta, GA) lectures", "Masjid Rahmah (New Jersey) lectures", "1st Muslim Masjid (Pittsburgh, PA) lectures", "Germantown Masjid (Philadelphia, PA) lectures", "MPUBS (Trinadad and Tabago) lectures", "UK lectures"};
        ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter<String>(this, simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(this);
        int channel = Arrays.asList((getResources().getStringArray(R.array.radios_array))).indexOf(app_name);

        //initialize views
        initializeViews();
    }

    public void initializeViews(){
        songName = (TextView) findViewById(R.id.songName);
        radioInfo = (TextView) findViewById(R.id.radioInfo);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        finalTime = mediaPlayer.getDuration();
        //duration = (TextView) findViewById(R.id.songDuration);
        seekbar = (SeekBar) findViewById(R.id.seekBar);
        songName.setText("Dawah Radio 24-7-12");

        seekbar.setMax((int) finalTime);
        seekbar.setClickable(false);
    }

    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
        //mediaPlayer.release();

        switch (position) {

            case 0:
                // Whatever you want to happen when the first item gets selected
                //mediaPlayer.release();
                //url = "http://radio.miraath.net:7000";
                url = "http://api.spreaker.com/listen/episode/6883149/shoutcast?force_http=true";
                radioInfo.setText("Masjid Al-tawheed Radio");
                Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
                break;
            case 1:
                // Whatever you want to happen when the second item gets selected
                //mediaPlayer.release();
                url = "http://api.spreaker.com/listen/episode/6888856/shoutcast?force_http=true";
                radioInfo.setText("Masjid Rahmah (New Jersey)");
                Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
                break;
            case 2:
                // Whatever you want to happen when the thrid item gets selected
                //mediaPlayer.release();
                //url = "http://radio.miraath.net:7020";
                url = "http://api.spreaker.com/listen/episode/6877902/shoutcast?force_http=true";
                radioInfo.setText("al-Masjid al-Awwal(Pittsburgh)");
                Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
                break;

            case 3:
                // Whatever you want to happen when the thrid item gets selected
                //mediaPlayer.release();
                url = "http://api.spreaker.com/listen/episode/6545744/shoutcast?force_http=true";
                radioInfo.setText("Germantown Masjid (Philadelphia)");
                Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
                break;
            case 4:
                // Whatever you want to happen when the thrid item gets selected
                //mediaPlayer.release();
                url = "http://mixlr.com/mpubs/showreel/those-who-rectify-themselves-and-the-people-when-the-people-become-corrupt-by-shaykh-mustafa-mubram/";
                radioInfo.setText("MPUBS (Trinadad and Tabago)");
                Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
                break;

            case 5:
                // Whatever you want to happen when the thrid item gets selected
                //mediaPlayer.release();
                //url = "http://radio.miraath.net:7040";
                url = "http://37.59.4.122:7040";
                radioInfo.setText("UK lectures");
                Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    // play mp3 song
    public void play(View view)
    {
        if (!mediaPlayer.isPlaying())
        {
            Toast.makeText(getApplicationContext(), "Radio selected. Buffering Now...", Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), "This may take a few moments. Please wait ...", Toast.LENGTH_LONG).show();
        }

        duration = (TextView) findViewById(R.id.songDuration);
        try
        {
            if (mediaPlayer.isPlaying())
            {
                mediaPlayer.stop();
                mediaPlayer.reset();
                //mediaPlayer.release();
                mediaPlayer.setDataSource(url);
                mediaPlayer.setOnPreparedListener(this);
                mediaPlayer.prepareAsync();
            }

            else if (!mediaPlayer.isPlaying()) {
                mediaPlayer.setDataSource(url);
                mediaPlayer.setOnPreparedListener(this);
                mediaPlayer.prepareAsync();
            }
        }

        catch (IllegalArgumentException e)
        {
            Toast.makeText(getApplicationContext(), "Radio not Available. Please try again Later.", Toast.LENGTH_LONG).show();

        } catch (SecurityException e) {
            Toast.makeText(getApplicationContext(), "Radio not Available. Please try again Later.", Toast.LENGTH_LONG).show();

        } catch (IllegalStateException e) {
            Toast.makeText(getApplicationContext(), "Radio not Available. Please try again Later.", Toast.LENGTH_LONG).show();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //handler to change seekBarTime
    private Runnable updateSeekBarTime = new Runnable() {
        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        public void run() {
            //get current position
            timeElapsed = mediaPlayer.getCurrentPosition();
            //set seekbar progress
            seekbar.setProgress((int) timeElapsed);
            //set time remaing
            double timeRemaining = finalTime - timeElapsed;
            duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
            //repeat yourself that again in 100 miliseconds
            durationHandler.postDelayed(this, 100);
        }
    };

    // pause mp3 song
    public void pause(View view) {

        Toast.makeText(getApplicationContext(), "Audio Paused ...", Toast.LENGTH_LONG).show();
        mediaPlayer.reset();
    }

    // go forward at forwardTime seconds
    public void forward(View view) {
        //check if we can go forward at forwardTime seconds before song endes
        if ((timeElapsed + forwardTime) <= finalTime) {
            timeElapsed = timeElapsed + forwardTime;

            //seek to the exact second of the track
            mediaPlayer.seekTo((int) timeElapsed);
        }
    }

    // go backwards at backwardTime seconds
    public void rewind(View view) {
        //check if we can go back at backwardTime seconds after song starts
        if ((timeElapsed - backwardTime) > 0) {
            timeElapsed = timeElapsed - backwardTime;

            //seek to the exact second of the track
            mediaPlayer.seekTo((int) timeElapsed);
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();
        timeElapsed = mediaPlayer.getCurrentPosition();
        seekbar.setProgress((int) timeElapsed);
        durationHandler.postDelayed(updateSeekBarTime, 100);

    }

}

谢谢。

ironmantis7x

问题不在 Fragment 中,而是在 DuaatRadio Activity 代码中,

在这一行

Spinner dropdown = (Spinner)findViewById(R.id.spinner1);

您正在尝试从 activity_main 布局中获取 ID 为 spinner1dropdown Spinner。但它没有在那里定义,所以它将 return null.

下一行:

dropdown.setAdapter(adapter);

您正在尝试 setAdapter null object。结果 NullPointerException.

您已在片段 class 中定义了微调器。因此,应在片段 class 中而不是 activity 中为微调器设置数据。