2014-04-09 58 views
-1

我有一個問題,當我在TextView中調用findViewById時會拋出NullPointerException,但不會爲其他元素。我已經嘗試了任何東西(更改標識符,調用OnCreateView,清理和生成項目),我不知道該怎麼做。Android:調用findviewbyid時的空異常

這是我的活動

public class RoutesActivity extends Activity {  

ListView routesList; 
EditText searchTxt; 
TextView noneRouteTxt; 
long uuid; 



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

    noneRouteTxt = (TextView)this.findViewById(R.id.notroute_txt); 
    getControls(); 
    Bundle extra = this.getIntent().getExtras(); 
    getRoutesList(extra); 
} 

,這是我的佈局:activity_routes.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context="com.geochild.app.com.geochild.app.activitities.RoutesActivity">  

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="325dp" 
    android:background="@drawable/app_background_waves" 
    android:layout_above="@+id/linearLayout" 
    android:layout_below="@+id/header_layout"> 

    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/routes_listview" 
     android:visibility="invisible"> 
    </ListView> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/no_routes" 
     android:id="@+id/notroute_txt" 
     android:visibility="invisible" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 
</RelativeLayout> 

你能幫助我嗎?謝謝

+2

發佈堆棧跟蹤,並指出您的代碼中哪些行正在被引用。 – azurefrog

+0

確保res/layout,res/layout-v14等中的每個佈局'activity_routes'都有notroute_txt定義。否則,如果使用不具有NPE的佈局,您將獲得NPE。 –

回答

0

NPE顯然會拋在下面一行。但是你也應該展示堆棧跟蹤的第一行。

noneRouteTxt = (TextView)this.findViewById(R.id.notroute_txt); 

而NPE,是因爲拋出,呼喚你的onCreate()方法時,應用程序使用的佈局是一個又一個,而不是「activity_routes」,其中ID notroute_txt不存在。

您使用了多少個佈局或者您是否已將其複製到res文件夾中?