简体   繁体   中英

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() . The value of this variable is taken from another class using Intent .

But I'm not able to get the value of that variable in the btnNext() method.

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.

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. But, better way would be to use Serializable or Parcelable to pass it.

Use it

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

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

mySongs = new ArrayList(); ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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