Android Activity findviewbyid () - null

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class FileExplorerActivity extends Activity 
{
    public static final String TAG="ricky";
    Button button;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        button = (Button) findViewById(R.id.but);<<<------------------
        if(button == null)
        Log.d(TAG, "FileExplorerActivity: button is null");
    }
    public FileExplorerActivity()
    {
       Log.d(TAG, "FileExplorer: constructor()");
    }
}

This is a simple operation that is triggered by another activity using Intent.

Intent openFileBrowser = new Intent(this, FileExplorerActivity.class);
try
{
    startActivity(openFileBrowser); 
}

After running the code, my LogCat file says "the button is null." Why???

+3
source share
3 answers

As pointed out by others, you did not set the layout through setContentView()before the call findViewById().

Why do I need it?

Because it Activity.findViewById()searches in the hierarchy for the representation of current activity. If you do not define a hierarchy of views, there is nothing to find. And when this method finds nothing, it returns null.

Therefore, you must add a layout after calling super.onCreate()

super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);

button = (Button) findViewById(R.id.but);
// ... 
+12
source

You need to set the layout

setContentView(R.layout.main_layout);
+1
source

(Xamarin Android)

public class MainActivity : WearableActivity
{
    ...

    OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        **SetContentView(Resource.Layout.RoundMain);**

        // Does not return null anymore:

        FindViewById<Button>(Resource.Id.ButtonVgOk).LongClick += (s, e) => ButtonVgOkOnLongClick();

        ...
   }
0

All Articles