【发布时间】:2017-11-27 05:20:45
【问题描述】:
我正在尝试将数据从活动发送到 BroadcastReceiver 类,然后再从接收器类发送到服务类。第一次数据正常,但之后它给出 nullPointer 异常
这是我的活动代码:-
public void onClick(View view) {
Intent i=new Intent();
i.setClass(MainActivity.this, Myreceiver.class);
i.putExtra("name",et.getText().toString().trim());
sendBroadcast(i);
et.setText("");
}
在 Myreceiver 类中
public void onReceive(Context context, Intent intent) {
String data=intent.getExtras().getString("name");
SharedPreferences sp=context.getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
Intent i=new Intent(context,MyService.class);
if (!data.equals("") && !data.isEmpty())
{
editor.putString("data",data).commit();
i.putExtra("names",data);
Log.e("Myreceiver data is ",data);
}
else {
String name = sp.getString("data", "");
i.putExtra("names",name);
Log.e("Myreceiver data is not",name);
}
context.startService(i);
}
在我的服务类中
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
name=intent.getExtras().getString("names");\\Line 40
Log.e("MyService class",name);
通常当活动的接收者在后台时,它第二次在上面的行给出空指针
错误日志:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.evoqis.trnode.MyService.onStartCommand(MyService.java:40)
谢谢:)
【问题讨论】:
-
你从哪里得到空指针?
-
@naveen 在服务类中,我使用意图获取名称。 Getextras()
-
@mitesh.. 我用过。提交()
-
你的
targetSdkVersion是什么?并发布错误日志。 -
已发布错误日志
标签: android service broadcastreceiver sharedpreferences