Skip to content

Instantly share code, notes, and snippets.

@udacityandroid
Last active May 19, 2023 05:51
Show Gist options
  • Save udacityandroid/f4ec40027031ba7de9352465f143c816 to your computer and use it in GitHub Desktop.
Save udacityandroid/f4ec40027031ba7de9352465f143c816 to your computer and use it in GitHub Desktop.
Miwok app: Cleaning up MediaPlayer resources
/**
* Clean up the media player by releasing its resources.
*/
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mMediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mMediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mMediaPlayer = null;
}
}
@Ahmad782
Copy link

Ahmad782 commented Jun 2, 2021

Whoah!

@GULLAGOWTHAM
Copy link

What are you trying after this android development course guys!!!!!

@Pratyush219
Copy link

package com.example.android.miwok;
import android.content.ClipData;
import android.content.Context;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class WordAdapter extends ArrayAdapter {

private int mColorResourceId;

public WordAdapter(@NonNull Context context,  @NonNull ArrayList<Word> objects, int colorResourceId) {
    super(context, 0, objects);
    mColorResourceId = colorResourceId;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if the existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
    if(listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }

    // Get the {@link AndroidFlavor} object located at this position in the list
    final Word currentWord = getItem(position);

    // Find the TextView in the list_item.xml layout with the ID version_name
    TextView nameTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
    // Get the version name from the current AndroidFlavor object and
    // set this text on the name TextView
    nameTextView.setText(currentWord.getMiwokTranslation());

    // Find the TextView in the list_item.xml layout with the ID version_number
    TextView numberTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
    // Get the version number from the current AndroidFlavor object and
    // set this text on the number TextView
    numberTextView.setText(currentWord.getDefaultTranslation());


    // Find the ImageView in the list_item.xml layout with the ID list_item_icon
    ImageView iconView = (ImageView) listItemView.findViewById(R.id.Image);
    // Get the image resource ID from the current AndroidFlavor object and
    // set the image to iconView
    if(currentWord.hasImage()) {
        iconView.setImageResource(currentWord.getImageResourceId());
        iconView.setVisibility(View.VISIBLE);
    }
    else{
        iconView.setVisibility(View.GONE);
    }

    //Adding Color to the list items
    View textContainer = listItemView.findViewById(R.id.text_container);

    int color = ContextCompat.getColor(getContext(), mColorResourceId);

    textContainer.setBackgroundColor(color);

    //Adding the audio files to each list item and making them play onClick
    LinearLayout clickItem = (LinearLayout) listItemView.findViewById(R.id.item);



    clickItem.setOnClickListener(new View.OnClickListener() {

        MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getAudioResourceId());
        @Override
        public void onClick(View view) {

            mediaPlayer.start();
        }
        /**
         * Clean up the media player by releasing its resources.
         */
        private void releaseMediaPlayer() {
            // If the media player is not null, then it may be currently playing a sound.
            if (mediaPlayer != null) {
                // Regardless of the current state of the media player, release its resources
                // because we no longer need it.
                mediaPlayer.release();

                // Set the media player back to null. For our code, we've decided that
                // setting the media player to null is an easy way to tell that the media player
                // is not configured to play an audio file at the moment.
                mediaPlayer = null;
            }
        }
    });

    // Return the whole list item layout (containing 2 TextViews and an ImageView)
    // so that it can be shown in the ListView
    return listItemView;
}

}
Guys I instead of making the MediaPlayer Object inside each activity created it inside the WordAdapter Class and I also set the onClickListener inside it and found that it works completely fine

Nice work I made it like that as well but I for some reason I'm not able to add the release method it says that it has to be an array or something
but I have an advice for you instead of making a new MediaPlayer every time the user click the view you can move it out of the OnClickListener but you have to make it 'final' like this final MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getVoiceResourceID());

and every time a user click you only select the correct sound by using mediaPlayer.selectTrack()

and that piece of code will be like this :

` final MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getVoiceResourceID());

    // Wait for user's input by his click on the list's item to play the sound.
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Storing the return value of getVoiceResourceID() into mVoice.
            // I think this line can be ignored so we call the method inside the creation of the Media Player.
            // Creating our media player and put our track on it.
            mediaPlayer.selectTrack(currentWord.getVoiceResourceID());
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                            // Regardless of the current state of the media player, release its resources
                            // because we no longer need it.
                            mediaPlayer.release();
                }
            });
        }
    };

`

but my problem with that is when I have that mediaPlayer.release(); line and I try to click more than one view at a time the app crashes and I can't fix that.

package com.example.android.miwok;

import android.content.ClipData;
import android.content.Context;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class WordAdapter extends ArrayAdapter {

private int mColorResourceId;

public WordAdapter(@NonNull Context context,  @NonNull ArrayList<Word> objects, int colorResourceId) {
    super(context, 0, objects);
    mColorResourceId = colorResourceId;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if the existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
    if(listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }

    // Get the {@link AndroidFlavor} object located at this position in the list
    final Word currentWord = getItem(position);

    // Find the TextView in the list_item.xml layout with the ID version_name
    TextView nameTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
    // Get the version name from the current AndroidFlavor object and
    // set this text on the name TextView
    nameTextView.setText(currentWord.getMiwokTranslation());

    // Find the TextView in the list_item.xml layout with the ID version_number
    TextView numberTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
    // Get the version number from the current AndroidFlavor object and
    // set this text on the number TextView
    numberTextView.setText(currentWord.getDefaultTranslation());


    // Find the ImageView in the list_item.xml layout with the ID list_item_icon
    ImageView iconView = (ImageView) listItemView.findViewById(R.id.Image);
    // Get the image resource ID from the current AndroidFlavor object and
    // set the image to iconView
    if(currentWord.hasImage()) {
        iconView.setImageResource(currentWord.getImageResourceId());
        iconView.setVisibility(View.VISIBLE);
    }
    else{
        iconView.setVisibility(View.GONE);
    }

    //Adding Color to the list items
    View textContainer = listItemView.findViewById(R.id.text_container);

    int color = ContextCompat.getColor(getContext(), mColorResourceId);

    textContainer.setBackgroundColor(color);

    //Adding the audio files to each list item and making them play onClick
    LinearLayout clickItem = (LinearLayout) listItemView.findViewById(R.id.item);



    clickItem.setOnClickListener(new View.OnClickListener() {

        MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getAudioResourceId());
        @Override
        public void onClick(View view) {

            mediaPlayer.start();
        }
        /**
         * Clean up the media player by releasing its resources.
         */
        private void releaseMediaPlayer() {
            // If the media player is not null, then it may be currently playing a sound.
            if (mediaPlayer != null) {
                // Regardless of the current state of the media player, release its resources
                // because we no longer need it.
                mediaPlayer.release();

                // Set the media player back to null. For our code, we've decided that
                // setting the media player to null is an easy way to tell that the media player
                // is not configured to play an audio file at the moment.
                mediaPlayer = null;
            }
        }
    });

    // Return the whole list item layout (containing 2 TextViews and an ImageView)
    // so that it can be shown in the ListView
    return listItemView;
}

}

Guys I instead of making the MediaPlayer Object inside each activity created it inside the WordAdapter Class and I also set the onClickListener inside it and found that it works completely fine

You can do that but as far as I understand, a new MediaPlayer object will be created for each list item view which won't be so memory-efficient. By declaring it in activities, you create that object just once for each activity and use the same object with different audio files for different list items.

@MatuP1
Copy link

MatuP1 commented Jun 25, 2021

Using the lockdown to learn

@PranavSangave
Copy link

Me too.

@shubham-0707
Copy link

It looks like i am the first here.

HaHaHa

@mateendev3
Copy link

I am the last one here i think :D

@shashankpandey43
Copy link

I am the last one here i think :D

no you r not

@rishikesh953
Copy link

Last one is me

@Abhay-Hasrani
Copy link

i am last second... no "one can prove me wrong but may be two can lol

@Lalithsha
Copy link

op

@taroon332
Copy link

last one

@DrKira1995
Copy link

NO ONE CAN BEAT ME ... LAST COMMENT

@Thorium09
Copy link

I am Last

Siuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

@syphaxalili
Copy link

But it's me the winner 🙋🏻‍♂️🙋🏻‍♂️

@JuniiiSays
Copy link

JuniiiSays commented Aug 23, 2022

@syphaxal I'm here after you So technically I'm the new winner here

@yatiksihag01
Copy link

@JuniiiSays Well, not anymore...... HAHAHAHA

@Aayuu
Copy link

Aayuu commented Oct 6, 2022

@qureshiwaqas Me who is last everywhere - (Ah shit! here we go again) o_o

@manansood60
Copy link

Beat Me, the new winner ✌

@Presheda
Copy link

That didn't last long

@manansood60
Copy link

You got me 👍

@victorcocuz
Copy link

what's with this? this is a reaaaally old udacity nanodegree android app

@JonathanSum
Copy link

JonathanSum commented Apr 1, 2023

image
Time to celebrate🥳🎉🎊🪅

@Vipxpert
Copy link

Heh! You're too early !!

@slxny
Copy link

slxny commented May 19, 2023 via email

@slxny
Copy link

slxny commented May 19, 2023 via email

@slxny
Copy link

slxny commented May 19, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment