开发者

findViewById Returns An Error

开发者 https://www.devze.com 2023-04-10 06:18 出处:网络
findViewById gives out an error, I think it\'s because it\'s returning null. My app is forced to close.

findViewById gives out an error, I think it's because it's returning null. My app is forced to close.

SensorManager sensorManager=null;

TextView x= null;
TextView y= null;
TextView z= null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    setContentView(R.layout.main);
    x= (TextView) findViewById(R.id.tv1);
    y= (TextView) findViewById(R.id.tv2);
    z= (TextView) findViewById(R.id.tv3);
}

XML:

<TextView
    android:id="@+id/tv1"
    android:layout_x="10px"开发者_Python百科
    android:layout_y="550px"
    android:text="@string/x"
    />  
<TextView
    android:id="@+id/tv2"
    android:layout_x="100px"
    android:layout_y="550px"
    android:text="@string/y"
    />  
<TextView
    android:id="@+id/tv3"
    android:layout_x="200px"
    android:layout_y="550px"
    android:text="@string/z"
    />

Can someone please tell me what I'm doing wrong?

SOLVED!

I used the XML given by Sunny at the bottom! Thank you to all!


That's simple.... tv* is not in your layout!

Please post the layout, I am 100% sure it doesn't contain:

<TextView android:id="@+id/tv1"/>
<TextView android:id="@+id/tv2"/>
<TextView android:id="@+id/tv3"/>

Please also learn how to get a logcat before going further in android development! ;-)

Window -> Show View -> Logcat


yes above code working fine and xml file should be like this.

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
 <TextView 
 android:id="@+id/tv1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"></TextView>
 <TextView 
  android:id="@+id/tv2"
  android:layout_width="wrap_content"
   android:layout_height="wrap_content"></TextView>
  <TextView>
 android:id="@+id/tv3"
 android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
 </LinearLayout>


yes that problem and if with xml is not done then You import android.R; so that it will give error if xml you have remove that and import PACKAGENAME.R;


First : Verify that your TextView Are present on your layout : main.xml :

<TextView android:id="@+id/tv1" .../>
<TextView android:id="@+id/tv2" .../>
<TextView android:id="@+id/tv3" .../>

Second : reBuild your project by following this steps : Project ==> Clean ==> Select your project and click OK .


The reason why this happens is :

findViewById() will search for the TextViews in the View hierarchy established by setContentView(R.layout.main). So if the TextViews aren't in main.xml you will get a null

0

精彩评论

暂无评论...
验证码 换一张
取 消