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

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

问题描述

我的alarmManager在MainActivity中,它每30秒触发一次MyReceiver类,然后从其中启动GetLLRD IntentService类.此后,我将来自onHandleIntent方法的请求发送到服务器,随后我收到响应.现在,我想实现以下目标,每当AlarmManager在MainActivity中触发时,我都希望将Intent从GetLLRD类中的服务器的响应传递到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);Map活动中我仅收到一次意图.有了这个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)

MainActivity:

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

        }

    }

};

推荐答案

您的体系结构存在缺陷.调用startService()时将创建IntentService.然后在服务中调用onCreate()onHandleIntent(). onHandleIntent()完成后,如果没有其他待处理的意图要处理,则服务将停止.

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 之前拨打此电话,

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.

在服务和活动之间实现通信的最佳方法是以下之一:

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

  1. 服务使用数据发送广播Intent.该活动可以注册一个BroadcastRecevier来监听它.

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

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

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.

在这两种情况下,服务都不需要了解有关活动的任何信息,并且活动不需要对服务的引用.

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.

添加代码以启动活动"

如果要启动活动,可以在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的实例在运行).如果活动已经在运行,则可以通过覆盖活动中的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将数据从服务发送到活动.

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天全站免登陆