传递位置与来自不同类的处理程序

时间:2014-01-28 20:35:18

标签: java android

我是Handlers概念的新手,我在android中看到了很多关于处理程序的例子。尽管有2个线程都在activity类中开始,我想从另一个名为Locac的类传递位置但是它给了我NullPointer异常。

这是Activity类

    Looper lupy;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


dbadapter mkola=new dbadapter(MainActivity.this);
mkola.openToWrite();






 Handler nok=new Handler(lupy) {

     public void handleMessage(Message msg)


    {

        Location locator=(Location)msg.obj;
        float lat=(float)(locator.getLatitude());

    }

};

这里是位置类(为了简单起见,我故意没有包含任何线程)

public class  locac implements LocationListener  {

public Context Ctx;
Handler nok;
public static String okai="Ctx.LOCATION_SERVICE";


public static String moi="manag.GPS_PROVIDER";

public locac (Context context)


{
this.Ctx=context;

}

@Override
public void onLocationChanged(Location loc) {
    // TODO Auto-generated method stub


     LocationManager manag;

     manag=(LocationManager)Ctx.getSystemService(okai);

     Message kol=new Message();
     kol.obj=loc;
     nok.sendMessage(kol);
}

我进入LogCat

 caused by: java.lang.NullPointerException
at android.os.Handler.<init>(Handler.java:226)
at android.os.Handler.<init>(Handler.java:134)
at com.example.alarma.MainActivity$1.<init>(MainActivity.java:39)
at com.example.alarma.MainActivity.onCreate(MainActivity.java:39)

1 个答案:

答案 0 :(得分:0)

此处还有其他问题,但主要问题是您的处理程序未初始化。在构建Object

时,您需要从活动中传递它
public class  locac implements LocationListener  {

public static String okai="Ctx.LOCATION_SERVICE";
public static String moi="manag.GPS_PROVIDER";

public Context Ctx;
Handler nok;

public locac (Context context, Handler handler){
     this.Ctx=context;
     this.nok = handler;
}

@Override
public void onLocationChanged(Location loc) {
    // TODO Auto-generated method stub


     LocationManager manag;

     manag=(LocationManager)Ctx.getSystemService(okai);

     Message kol=new Message();
     kol.obj=loc;
     nok.sendMessage(kol);
}