Toast和startActivity在片段中工作,但在类中不工作



我无法让Toast和startActivity在VLC.java类中工作。如果将这两个语句放在TerminalFragment.java类中,它们都可以工作。

安卓工作室报告没有问题,但当我运行应用程序时,它崩溃了。

我尝试了所有可能的getActivity、startActivity和Context排列,但都不起作用。我怎样才能让它发挥作用?

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);
}
}

我刚刚测试了上述VLC类和RadioStream方法中的Toast

我认为问题与如何在onCreate中调用方法有关。

确保你没有做

new VLC().RadioStream()

因为新的VLC对象将没有附加上下文,并且您将通过调用getApplicationContext((获得一个空指针异常

我设法让它按如下方式工作:

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);
}
}

最新更新