2011-03-22 80 views
0

嗨,我是一名新開發人員。在我的應用程序中,我試圖展示一個地方的經緯度。當應用程序啓動時,自動我想要顯示的值以下是我的代碼。如何在android中啓動活動時顯示值

{ 
    setContentView(R.layout.main); 

     if(entered) 
     { 
      loadCoords(); 
     } 
     Coords coords = loadCoords(); 


    } 

    private Coords loadCoords() 
    { 
     TextView latText = (TextView) findViewById(R.id.latText); 
     TextView lngText = (TextView) findViewById(R.id.lngText); 
     LocationManager myManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
     if(myManager != null){ 
      //List list = myManager.getAllProviders(); 
      String param = (String)myManager.getProviders(true).get(0); 
      Location loc = myManager.getLastKnownLocation(param); 
      if(loc != null){ 
       Double latPoint = loc.getLatitude(); 
       Double lngPoint = loc.getLongitude(); 
        try { 
         latText.setText(latPoint.toString()); 
         lngText.setText(lngPoint.toString()); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
      } 
      else 
        Log.e("AndroidMaps ","Error: Location is null"); 
     } 
     else 
      Log.e("AndroidMaps ","Error: Location Manager is null"); 
     return null; 

    } 
} 

但我的應用程序崩潰時,我試圖在設備中運行它。

以下是logcat的

ERROR/AndroidRuntime(6311): Uncaught handler: thread main exiting due to uncaught exception 
ERROR/AndroidRuntime(6311): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gis.ss/com.gis.ss.main}: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0 
ERROR/AndroidRuntime(6311): Caused by: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0 

表示任何人都可以給我解釋一下什麼是錯誤的錯誤... plzzz

+2

爲什麼你的函數loadCoords()應該返回Coords,但你總是返回null?如果你返回void並寫入loadCoords();而不是Coords coords = loadCoords();怎麼了? – jcfrei 2011-03-22 10:07:51

回答

1

你可能會得到這裏空單: String param = (String)myManager.getProviders(true).get(0);,並試圖得到第一個列表的原因java.lang.IndexOutOfBoundsException嘗試 <uses-permission android:name="android.permission.ACCESS_GPS" /><uses-permission android:name="android.permission.ACCESS_LOCATION " />添加到您的menifest。

+0

也添加' Harshad 2011-03-22 10:11:16

0

看起來你沒有得到有效的位置。

你打開你的GPS嗎?

如果您在Emulator上運行它,那麼您必須在DDMS - > Emulator Control - > Location Controls中設置您的位置。