SharedPreferances在下一个活动中给出空值

时间:2017-11-27 05:20:45

标签: android service broadcastreceiver sharedpreferences

我正在尝试将数据从活动发送到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)

感谢:)

3 个答案:

答案 0 :(得分:0)

在handleIntent和onStartCommand上使用此代码获取意图。

protected void onStartCommand (Intent intent, int flags, int startId) {
    data=(String) intent.getExtras().get("data"); 
}

答案 1 :(得分:0)

您正在接收数据包

intent.getExtras().getString("name"); //using getExtras() receives bundle 

但是你发送没有捆绑的数据,

i.putExtra("name",et.getText().toString().trim());

添加额外内容而非额外内容。象 -

Bundle bundle = new Bundle();
bundle.putString("name", et.getText().toString().trim());
i.putExtras(bundle);

答案 2 :(得分:0)

而不是getExtras()更改为getStringExtra()。

MyReceiver Class

public void onReceive(Context context, Intent intent) 
{
 String data=intent.getStringExtra("name");
 ...
}

MyService Class

public int onStartCommand(Intent intent, int flags, int startId) 
{
 name=intent.getStringExtra("names");
 ...
}