Dustin Kazi
Dustin Kazi

Reputation: 13

mContext Type Mismatch when used with Audio Service

I am currently following the Android Developer Tutorial on dev.android.com. I am stuck on the audio part. Here is the code I have:

package com.example.myfirstapp;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity
{
  Context mContext;

  public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mContext = this.getApplicationContext();
    }


    @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;
    }
    
    public void sendMessage(View view)
    {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        Intent.putExtra(EXTRA_MESSAGE, message);
        StartActivity(intent);
    }
    
    public void playSong()
    {
        AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
    }
}

In the function playSong(), mContext is a Type Mismatch.

What can I do to fix this problem to where I can achieve fully functioning code described here.

Thanks! -Dustin

Upvotes: 1

Views: 1132

Answers (1)

A--C
A--C

Reputation: 36449

You will need to cast.

AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

getSystemService() returns an Object, it is up to you to properly cast it to use the specific methods of whatever service you're attempting to use. This is the standard way to get references to system services in Android.

Upvotes: 3

Related Questions