user2726232
user2726232

Reputation: 131

How to get rid of an instance of an object in java?

I NEED to delete an instance of a class in java so I can make a new instance. The previous instance must be destroyed before I can continue. I realize that Java doesn't provide for an implicit delete, and I've been trying to force garbage collection to get rid of it using a trick with a weak reference.

This is my code:

private static void gc() {
    Object obj = new Object();
    WeakReference ref = new WeakReference<Object>(obj);
    obj = null;
    while(ref.get() != null) {
        System.gc();
    }
}

private void setTrack(String path){
    MediaHub current;
    if(!isPlaying){
        current = new MediaHub(title,album,titles,titlePlace,play,next,previous,volume,progress,songTitle,thisInstance,getBaseContext(),path);
    } else {
        current = null;
        gc();
        isPlaying = false;
        setTrack(path);
    }
}

MediaHub is the object I'm trying to delete an instance of and make a new one. isPlaying is a boolean instance variable defined as false at the top the class. Supposedly, the method gc() should force a garbage collection.

So far, I've had no success (for hopefully obvious reasons). So, how do I delete an instance of MediaHub?

EDIT: The reason I need it deleted is because there is an android MediaPlayer used in MediaHub and when I need to switch songs I end up with two songs playing over each other. I'm sort of in deep with the code and I don't want to rewrite a ton of code. So I'm really hoping for an answer here...

Upvotes: 2

Views: 407

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006869

So, how do I delete an instance of MediaHub?

You don't.

The reason I need it deleted is because there is an android MediaPlayer used in MediaHub and when I need to switch songs I end up with two songs playing over each other.

Then you write a method on MediaHub, such as switchSongs(), that calls the appropriate methods on MediaPlayer to stop() the current song and prepare() (or prepareAsync()) the next song.

Upvotes: 7

Related Questions