简体   繁体   English

如何从“ onCreate()”访问同一类的另一个方法中的Arraylist变量?

[英]How to access from “onCreate()” an Arraylist variable in another method of same class?

I want to access an Arraylist variable ( mySongs ) declared globally and used in the onCreate() method in another method called btnNext() . 我想访问一个全局声明的Arraylist变量( mySongs ),该变量在另一个称为btnNext()方法的onCreate()方法中使用。 The value of this variable is taken from another class using Intent . 此变量的值使用Intent从另一个类中获取。

But I'm not able to get the value of that variable in the btnNext() method. 但是我无法在btnNext()方法中获取该变量的值。

Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos",0);

It's giving a null pointer exception on this variable. 它为此变量提供了一个空指针异常。 When checked in the Log, it's showing 'null' in the method whereas when checked on Log outside the btnNext() method, it works fine. 在Log中检查时,在方法中显示为“ null”,而在btnNext()方法之外在Log上检查时,它可以正常工作。

public void btnNext(){
    Log.d("DATA", "songs"+mySongs);

    if(isRepeat==true || isShuffle==true)
    {
        isRepeat = false;
        btnRepeat.setImageResource(R.drawable.btn_repeat_default);

        isShuffle = false;
        btnShuffle.setImageResource(R.drawable.btn_shuffle_default);
    }
    mp.stop();
    mp.release();
    position = (position+1) % mySongs.size();
    Log.d("DATA", "p"+position);
    u = Uri.parse(mySongs.get(position).toString());
    mp = MediaPlayer.create(getApplicationContext(),u);
    displaySongName(position);
    mp.start();
    btnPlay.setImageResource(R.drawable.btn_pause);
    //Toast.makeText(this, "Method called", Toast.LENGTH_SHORT).show();
    Log.d("DATA", "p");    
}

What could be the problem? 可能是什么问题呢?

replace this 取代这个

mySongs = (ArrayList) b.getParcelableArrayList("songlist"); 

with this 有了这个

mySongs = new ArrayList<Object>(b.getParcelableArrayList("songlist"));

Make it public static and you will be able to pass your ArrayList to Another Class. 将其设为public static ,您将可以将ArrayList传递给另一个类。 But, better way would be to use Serializable or Parcelable to pass it. 但是,更好的方法是使用SerializableParcelable传递它。

Use it 用它

mySongs = new ArrayList<Object>(b.getParcelableArrayList("songlist"));

您在全局上声明了mySongs,但是是否在onCreate()中创建了它的实例?

mySongs = new ArrayList(); ?

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

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