-1

I have two activities first one has public String var called songurl and button leads to the second activity and second activity has mediaplayer receive URL from the String var which is in the first activity and then start playing but the problem is the mediaplayer doesn't work and I got an error

here is MainActivity1.kt or .java as your language :-

  lateinit var songurl :String
class MainActivity1 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    songurl = "https//...... My URL"

        var btnstart_MainActivity2:Button = findViewById(R.id.btn)
        btnstart_MainActivity2.setOnClickListener {
            startActivity(Intent(this,Main2Activity::class.java))
        }

    }
}

here is MainActivity2 :-

class Main2Activity : AppCompatActivity() {
    lateinit var mediaplayer: MediaPlayer
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            mediaplayer= MediaPlayer()
            mediaplayer.setDataSource(songurl)
            mediaplayer.prepare()
            mediaplayer.start()
        }
    }

and here is the err
lateinit property songurl has not been initialized

2 Answers2

0

Your problem is that your songurl is being present only in your first activity. There is no value and even assignment for it in activity 2.

Consider passing it as a intent's bundle parameter:

Activity1:
Bundle bundle= new Bundle();
bundle.putString("key", songurl);

Intent i = new Intent(Activity1.this,Activity2.class);
i.putExtras(bundle);
startActivity(i);

Activity2:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_activity);

    Bundle p = getIntent().getExtras();
    String songurl = p.getString("key");

}

Examples are in java.

Maksym V.
  • 2,877
  • 17
  • 27
0

You should send your songUrl in android Intent extras. The reason you are getting error is that it isn't defined in the activity2 you have defined it in activity1.

to send intent extra

var intent = Intent(this,Main2Activity::class.java)
intent.putExtra("songurl", songurl)

to get extra in other activity

if(getIntent().hasExtra("songurl"){
 var songurl = getIntent().getStringExtra("songurl")
}
Zubair Soomro
  • 180
  • 1
  • 12