Search code examples
javaandroidclassfragmenttoast

Toast and startActivity work in fragment but not class


I can't get the Toast and the startActivity to work in the VLC.java class. Both statements work if they are put in the TerminalFragment.java class.

Android Studio reports no problems but when I run the app it crashes.

I've tried about every possible getActivity, startActivity and Context permutation but nothing works. How can I get this to work?

TerminalFragment.java

receiveText.append(toCaretString(msg, newline.length() != 0));            
        Task(msg);
        // If I put the Intent and startActivity(play) here it works fine
    }
}

public void Task(String tsk) {
//  String id = tsk.substring(0, 2);
    String id = "01";
    String[] smallString = StringUtils.substringsBetween(tsk, ";", ";");

    switch (id)
    {
    // VLC
    case "01":
       VLC myObj = new VLC();
        myObj.RadioStream(smallString);
        break;
    case "02":
        Toast.makeText(getActivity(), id, Toast.LENGTH_SHORT).show();
        break;
    default:
       Toast.makeText(getActivity(), "default", Toast.LENGTH_SHORT).show();
        break;
    }
}

VLC.java

package com.android_usb_gateway;

import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

public class VLC extends MainActivity {

public void RadioStream(String[] args) {

    // Can not get the Toast to work
    Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();

    // Get the name and url
    String url = args[2];
    String name = args[3];
    String AUDIO_WILD = args[4];
    String TITLE = args[5];

    // The intent and startActivity(play) work fine if they are in   TerminalFrament.java
    Intent play = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.parse(url);
    play.setPackage(MainActivity.app);
    play.setDataAndType(uri, AUDIO_WILD);
    play.putExtra(TITLE, name);

    // Can not get this to work
    startActivity(play);
  }
}

Solution

  • I managed to get it working as follows:

    TerminalFragment.java

    VlcObject obj = new VlcObject(this);
    obj.RadioStream(smallString);
    

    VlcObject.java

    public class VlcObject {
        TerminalFragment c;
    
        public VlcObject(TerminalFragment c) {
            this.c = c;
        }
    
        public void RadioStream(String[] args) {
    
        Intent play = new Intent(Intent.ACTION_VIEW);
    
        c.startActivity(play);
        }
    }