空对象引用上的“java.lang.String android.content.Context.getPackageName()" [英] 'java.lang.String android.content.Context.getPackageName()' on a null object reference

查看:37
本文介绍了空对象引用上的“java.lang.String android.content.Context.getPackageName()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 alarmManager 在 MainActivity 中,它每 30 秒向 MyReceiver 类触发一次,然后我从它启动 GetLLRD IntentService 类.此后,我从 onHandleIntent 方法向服务器发送请求,然后我得到响应.现在我想实现以下目标,每次在 MainActivity 中触发 alarmManager 时,我都想将 GetLLRD 类中来自服务器的响应中的 Intent 传递给 Map 类.

My alarmManager is in the MainActivity it fires every 30 second to the MyReceiver class then from it I start the GetLLRD IntentService class. Thereafter, I am sending a request from the onHandleIntent method to the Server following which I am getting a Response. Now I want to achieve the following, every time the alarmManager fires in the MainActivity I want to pass the Intent from the Response from the Server in the GetLLRD class to the Map class.

我已经用 GetLLRD 类中的意图代码尝试了两次,这部分 Intent intent1 = new Intent(this, Map.class); 我在 中只收到了一次意图映射 活动.有了这个 Intent intent1 = new Intent(mContext, Map.class); 应用程序崩溃了,我在下面收到了这个错误.我怎样才能达到我的目的?

I have tried it twice with the intent's code in the GetLLRD class with this part Intent intent1 = new Intent(this, Map.class); I received the intent just once in the Map activity. With this one Intent intent1 = new Intent(mContext, Map.class); the app crashes and I got this error below. How can I achieve my purposes?

错误:

07-08 13:04:33.482: E/AndroidRuntime(16838): FATAL EXCEPTION: IntentService[IntentService]
07-08 13:04:33.482: E/AndroidRuntime(16838): Process: com.bustracker, PID: 16838
07-08 13:04:33.482: E/AndroidRuntime(16838): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
07-08 13:04:33.482: E/AndroidRuntime(16838):    at android.content.ComponentName.<init>(ComponentName.java:77)
07-08 13:04:33.482: E/AndroidRuntime(16838):    at android.content.Intent.<init>(Intent.java:4570)
07-08 13:04:33.482: E/AndroidRuntime(16838):    at com.bustracker.GetLLRD.onHandleIntent(GetLLRD.java:98)
07-08 13:04:33.482: E/AndroidRuntime(16838):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
07-08 13:04:33.482: E/AndroidRuntime(16838):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-08 13:04:33.482: E/AndroidRuntime(16838):    at android.os.Looper.loop(Looper.java:145)
07-08 13:04:33.482: E/AndroidRuntime(16838):    at android.os.HandlerThread.run(HandlerThread.java:61)

主要活动:

public class MainActivity extends ActionBarActivity{
        Context context;

                    getLRLD.received_MainActvity_Context(context);
                    Intent intent = new Intent(MainActivity.this,
                            IntentReceiver.class);
                    intent.putExtra("json_data", json);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(
                            getApplicationContext(), 1, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    Calendar cal = Calendar.getInstance();
                    alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                            System.currentTimeMillis(), 30 * 1000,
                            pendingIntent);
                  startService(intent);

 }

MyReceiver 类:

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String action = intent.getStringExtra("json_data");

            if (!action.isEmpty()) {

                startService(context, action);

            }
        } catch (Exception e) {
        }
    }

    public void startService(Context context, String action) {
        Intent inetent = new Intent(context, GetLLRD.class);
        inetent.putExtra("json_data", action);
        context.startService(inetent);
    }

}

GetLLRD 类:

public class GetLLRD extends IntentService {
    Context mContext;

    public GetLLRD() {
        super("IntentService");

    }
    public void received_MainActvity_Context(Context context){
        this.mContext = context;


    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String jSONString = intent.getStringExtra("json_data");

        if (jSONString != null) {
                 //So if I try it in this way I am just receiving the data intent just once in the Map activity.
                             Intent intent1 = new Intent(this, Map.class);
                             intent1.putExtra("list_data", data);
                             intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                             startActivity(intent1);

               //When I do it in this way I am getting the error above:
                             Intent intent1 = new Intent(mContext, Map.class);
                             intent1.putExtra("list_data", data);
                             intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                             mContext.startActivity(intent1);

        }
    }
 }

地图活动:

public class Map extends ActionBarActivity{

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Intent intent = getIntent();        
            @SuppressWarnings("unchecked")
             ArrayList<ItemDTO> list =(ArrayList<ItemDTO>) intent.getSerializableExtra("list_data");
                for (ItemDTO itemDTO : list) {
                    double latitude = itemDTO.getLatitude();
                    double longitude = itemDTO.getLongitude();
                    int route = itemDTO.getRoute();
                    String direction = itemDTO.getDirection();
                    System.out.println("test from Map activity:  " + latitude + ", " + longitude
                            + ", " + ", " + route + ", " + direction);

                }
        }       
    }

GetLLRD IntentService 类:

            if (data != null && !data.isEmpty()) {
                                            Intent localIntent = new Intent(
                                Constants.BROADCAST_ACTION).putExtra(
                                "data_list", data);
                        LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
            } 

在地图活动中:

onCraete(Bundle savedInstanceState){
        IntentFilter data_filter = new IntentFilter();
        data_filter.addAction(Constants.BROADCAST_ACTION);
        registerReceiver(data_receiver, data_filter);
}


final BroadcastReceiver data_receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        @SuppressWarnings("unchecked")
        ArrayList<ItemDTO> list = (ArrayList<ItemDTO>) intent
                .getSerializableExtra("list_data");
        for (ItemDTO itemDTO : list) {
            double latitude = itemDTO.getLatitude();
            double longitude = itemDTO.getLongitude();
            int route = itemDTO.getRoute();
            String direction = itemDTO.getDirection();
            System.out.println("test from Apple activity:  " + latitude
                    + ", " + longitude + ", " + ", " + route + ", "
                    + direction);

        }

    }

};

推荐答案

您的架构存在缺陷.IntentService 在您调用 startService() 时创建.然后 onCreate()onHandleIntent() 在服务中被调用.onHandleIntent() 完成后,如果没有其他待处理的 Intent,则服务停止.

Your architecture is flawed. The IntentService is created when you call startService(). Then onCreate() and onHandleIntent() is called in the Service. Upon completion of onHandleIntent(), if there are no other pending Intents to be processed the Service stops.

您在 MainActivity 之前 调用 startService() 之前进行此调用:

You are making this call in MainActivity before you call startService():

getLRLD.received_MainActvity_Context(context);

您没有展示如何设置参考变量 getLRLD,但这不会起作用.在您调用 startService() 之前,实际上不会创建服务.

You don't show how you are setting the reference variable getLRLD, but this isn't going to work. The Service isn't actually created until you call startService().

您正在尝试在服务和活动之间建立通信渠道.但是,您使用的是 IntentService,它是一种非持久性服务.它根据需要创建,当它无事可做时它就会消失.因此,您不能将服务的引用传递给活动,也不应将活动的引用传递给服务.

You are trying to establish a communcations channel between the Service and the Activity. However, you are using IntentService which is a non-persistent Service. It gets created as needed and when it has nothing to do it goes away. You therefore cannot pass a reference to the Service to the Activity, and you also should not pass a reference to the Activity to the Service.

实现 Service 和 Activity 之间通信的最佳方式是以下之一:

The best way to achieve communication between the Service and the Activity is one of the following:

  1. 服务发送带有数据的广播Intent.Activity 可以注册一个 BroadcastRecevier 来监听这个.

  1. Service sends a broadcast Intent with the data. The Activity can register a BroadcastRecevier to listen for this.

Activity 创建一个 PendingIntent 包含必要的 ACTION、COMPONENT 等,并将其作为 Intent 中的额外"传递给服务,当它使用时调用 startService().服务对该 PendingIntent 调用 send() 以将数据返回给 Activity.

Activity creates a PendingIntent containing the necessary ACTION, COMPONENT, etc. and passes this to the Service as an "extra" in the Intent it uses when calling startService(). The Service calls send() on that PendingIntent in order to return data to the Activity.

在这两种情况下,Service 都不需要知道关于 Activity 的任何信息,Activity 也不需要引用 Service.

In both cases the Service doesn't need to know anything about the Activity, and the Activity doesn't need a reference to the Service.

添加代码以启动活动

如果你想启动一个Activity,你可以在Service.onHandleIntent()中进行:

If you want to start an Activity, you can do this in the Service.onHandleIntent():

Intent intent1 = new Intent(this, Map.class);
intent1.putExtra("list_data", data);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
              Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent1);

使用 Intent.FLAG_ACTIVITY_SINGLE_TOP 将阻止 Android 启动 Activity 的新实例,如果已经有一个 Activity 实例正在运行.如果 Activity 已经在运行,您可以通过覆盖 Activity 中的 onNewIntent()Intent 中获取额外".

Using Intent.FLAG_ACTIVITY_SINGLE_TOP will prevent Android from launching a new instance of the Activity, if there is already an instance of the Activity running. In case the Activity is already running, you can get the "extras" from the Intent by overriding onNewIntent() in the Activity.

如果使用这种方法,则不需要使用广播 Intent 将数据从 Service 发送到 Activity.

If you use this approach you don't need to use the broadcast Intent to send the data from the Service to the Activity.

这篇关于空对象引用上的“java.lang.String android.content.Context.getPackageName()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆