在Eclipse的Java開發Android ...的Android getBaseContext getApplicationContext不工作
Context c = getBaseContext(); // returns null
Context c = this.getBaseContext(); // throws an exception.
Context c = getApplicationContext(); // throws an exception
Context c = this.getApplicationContext(); // throws an exception.
File f = getFilesDir(); // throws an exception
File f = this.getFilesDir(); // throws an exception
正如你可以看到我不能讓應用程序或在所有的基本上下文。嘗試獲取沒有它們的文件dir不起作用。我怎樣才能訪問我的文件目錄?
public class SoundHandler extends Activity {
private Button mButtonPlay;
private Button mButtonDone;
// private LinearLayout mOverallView;
private PeekActivity mHome;
private MyButtonListener myButtonListener;
private MediaPlayer mPlayer;
private File audioFilePath;
public SoundHandler(PeekActivity home) {
mHome = home;
myButtonListener = new MyButtonListener();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void open() {
mHome.setContentView(R.layout.sounds);
mButtonDone = (Button) mHome.findViewById(R.id.soundDone);
mButtonDone.setOnClickListener(myButtonListener);
mButtonPlay = (Button) mHome.findViewById(R.id.playSound);
mButtonPlay.setOnClickListener(myButtonListener);
mPlayer = null;
// This is what I thought would work, but it does not
audioFilePath = this.getBaseContext().getFilesDir().getAbsolutePath();
// These are my attempts to see what, if anything works and is not null
// but I've tried all the combinations and permutations above.
SoundHandler a = this;
Context b = getBaseContext();
Context c = getApplicationContext();
File d = this.getFilesDir();
// I'm really just trying to get access to an audio file that is included
// in my build in file /res/raw/my_audio_file.mp3
// mPlayer = MediaPlayer.create(this, R.raw.my_audio_file); doesn't work either
}
任何機會,你可以發佈您的代碼,所以我們得到你_where_的想法調用這些方法? IIRC'Contexts'應該保持爲null,直到你的Activity的超類「onCreate()'被調用。此外,您應該發佈已拋出的異常(帶有完整堆棧跟蹤)。 –
換句話說,你在哪裏打電話? – LuckyMe
您是否通過調用其構造函數來啓動該活動? –