有意图地传递数据
最近我一直在玩弄意图和捆绑。我以为我已经弄清楚了它们,但是在意图之间传递数据时我不断遇到问题我知道你必须使用捆绑包,但是当我尝试实现一个简单的程序来测试它时,我不断收到空指针异常。我制作的程序只是一个调用服务来创建字符串的活动,然后该活动应该能够获取该服务创建的字符串并对其进行烘烤。有谁知道我在这里做错了什么,为任何可以提供帮助的人欢呼。 下面的代码
这是Activity 类
MyIntent = new Intent(this, GetLocation.class);
startService(MyIntent);
bundle = MyIntent.getExtras();
test = bundle.getString("location");
Context context = getApplicationContext();
CharSequence text = test;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Service 类
Intent Int1 =new Intent(this,MapMock.class);
Bundle b = new Bundle();
String yeah = new String();
yeah = "hello";
b.putString("location", yeah);
Int1.putExtras(b);
Lately I have been playing around with intents and bundles. I thought I had them figured out, but I keep getting problems when passing data between intents I understand that you have to use bundles, but when I try implement a simple program to test this, I keep getting a null pointer exception. The program I made is just an activity which calls a service to create a string and then that activity should be able to get the string created by the service and toast it. Does anyone know what I am doing wrong here, cheers to anyone that can help. Here is the code below
Activity class
MyIntent = new Intent(this, GetLocation.class);
startService(MyIntent);
bundle = MyIntent.getExtras();
test = bundle.getString("location");
Context context = getApplicationContext();
CharSequence text = test;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Service class
Intent Int1 =new Intent(this,MapMock.class);
Bundle b = new Bundle();
String yeah = new String();
yeah = "hello";
b.putString("location", yeah);
Int1.putExtras(b);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
服务不是这样运作的。
您通过 startService 发送到服务的意图不会更新并返回到启动它的活动。
我认为您需要绑定服务。
请阅读此处了解更多信息。这允许您调用函数并将值传递回活动。
Services don't work this way.
The intent you send to the service via startService doesn't get updated and returned to the activity that starts it.
I think you need a bound service.
Read here to find out more. This allows you to call functions and pass values back to the activity.
看起来您正在访问尚未放入意图的意图日期,
就像您从服务启动活动并传递一些数据使用一样:
Looks like you are accessing intent date which you haven't put into intent,
like if you are starting activity from your service, and passing some data use: