2014-01-22 60 views
0

我有兩個類,一個是位置,第二個是MainActivity,我想要做的是使用位置中的方法獲取活動類中的緯度類,下面是位置類:活動中的另一個類的調用方法返回null

public class locac implements LocationListener { 
    public Context Ctx; 
    private final Context context; 

    public locac (Context context) { 
     this.context=Ctx; 
    } 

    public int GetLat() { 
     LocationManager manag; 
     manag=(LocationManager)Ctx.getSystemService(Ctx.LOCATION_SERVICE); 
     Location alfa=manag.getLastKnownLocation(manag.GPS_PROVIDER); 
     return (int) (alfa.getLatitude()); 
    } 

,這裏是在MainActivity類的部分

locac nova=new locac(this.m); 
int latitu=nova.GetLat(); 
Context m; 
Toast.makeText(getApplicationContext(), latitu, Toast.LENGTH_LONG).show(); 

我得到的錯誤是:

Caused by: java.lang.NullPointerException 
at com.example.alarma.locac.GetLat(locac.java:71) 

我猜的背景下返回null,但不明白爲什麼

PS

我加入的全部活動類:

public class MainActivity extends Activity { 

public static final String content="test"; 
public static final Integer kom=2; 
Context m; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


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


locac nova=new locac(MainActivity.this); 
int latitu=nova.GetLat(); 

Toast.makeText(getApplicationContext(), 
     latitu, Toast.LENGTH_LONG).show(); 


mkola.insert(content); 










} 



} 
+0

什麼是'this.m'?給變量一個體面的名字,而不是'm'。順便說一句,你應該閱讀[Java命名約定](http://www.oracle.com/technetwork/java/codeconv-138413.html)。 – m0skit0

+0

@Nfear感謝您的編輯。這是一個MESS! –

回答

2

在你的構造,該行:

this.context=Ctx; 

什麼都不做,因爲Ctxthis.context同時指向實例變量因此當你創建你的對象時(對象的默認值)是null

它應該是:

private final Context context; //remove this line 
public Context Ctx; 


public locac (Context context){ 
    this.Ctx = context; 
} 

另外要注意,getLastKnownLocation也可以返回null

P.S:嘗試尊重命名約定。

+0

@ m0skit0不,因爲他明確使用'this.',所以它指的是字段而不是構造函數參數。無論如何,這個任務都是交換的。 –

+0

感謝您的解釋,我做了更改,但該程序仍然崩潰與GetLat – user2557930

+0

@ user2557930 NullPointer正如我所說'getLaskKnownLocation'可以返回null。錯誤發生的路線是什麼?並且'this.m'不爲null? –

0

我沒有看到任何初始化Ctx。

public Context Ctx; 

public locac (Context context){ 
    this.context=Ctx; 
} 
相關問題