Question

Why findViewById throws NULL Exception?Here is layout and sourcecode file:

<RelativeLayout 
...
tools:context=".MainActivity" >

<TextView 
    android:id="@+id/usernameText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

And here is the source code in MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);      
    try{
        TextView text=(TextView)MainActivity.this.findViewById(R.id.usernameText);
        text.setText(10);
    }catch(Exception e){
        Log.i("Log", e.getMessage()+"Error!"); // LogCat message

    }

}

However, findViewById()returns null, and I don't know even why. This Code is so simple.

Was it helpful?

Solution

text.setText(10);

in this way you are looking for a String with id = 10; You should change in

 text.setText(String.valueOf(10));

OTHER TIPS

use this code................

public class MainActivity extends Activity {
    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text =(TextView)findViewById(R.id.usernameText);
        try{
            text.setText(String.valueOf(10));
        }catch(Exception e){
            Log.i("Log", e.getMessage()+"Error!"); // LogCat message
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top