0

I am trying to learn some java/android development, but I'm really struggling with the basics.

My code looks like this.

package com.example.app_james3;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    MediaPlayer media=MediaPlayer.create(this, R.raw.button);
    media.start();  // THIS LINE IS GIVING ERROR: Syntax error on token "start",    Identifier expected after this token

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Can anyone offer advice to get this very simple line working? I've copied others code, so I am fairly sure the syntax is correct.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Waller
  • 1,795
  • 4
  • 18
  • 35

2 Answers2

2

In Java, all statements (anything that doesn't declare a variable or class) have to go in methods or in a constructor. media.start(); is a statement. Therefore, you should put it in a method.

Because media.start(); should be executed close to startup time, put it in onCreate:

MediaPlayer media;

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

    // Your initialization code goes here:
    media = MediaPlayer.create(this, R.raw.button);
    media.start();
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Many thanks, I know it's frowned upon round these ways if this isn't already known... I can't accept your answer for a few minutes, but I'll accept shortly. – Waller Mar 31 '13 at 08:54
0

You have to declare variable inside the activity but when u initialize value from xml inside the function or after setcontentview. You have to also read below link :- Why does onClickListener not work outside of onCreate method?

When does Application's onCreate() method get called?

What's onCreate(Bundle savedInstanceState)

public class MainActivity extends Activity { 



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

MediaPlayer media=MediaPlayer.create(this, R.raw.button);
media.start();  // THIS LINE IS GIVING ERROR: Syntax error on token "start",    Identifier expected after this token
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
Community
  • 1
  • 1
duggu
  • 37,851
  • 12
  • 116
  • 113