Home > database >  startActivity(intent) not working when used along with data binding
startActivity(intent) not working when used along with data binding

Time:12-13

I have used data binding in my code. On using data binding startActivity(intent) is not taking me to the SecondActivity

MainActivity.java -

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private Data data = new Data();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.setData(data);
        binding.invalidateAll();

        data.setClickMe("Click Me");

        binding.button.setOnClickListener(view -> {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        });
    }
}

SeondActivity.java -

public class SecondActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private Data data = new Data();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_second);
        binding.setData(data);
        binding.invalidateAll();
        data.setHelloThere("Hello there");
    }
}

CodePudding user response:

Before using DataBinding, You have to set contentView like this with DataBinding -

....
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        setContentView(binding.root);     // here set the DataBinding root as content view
        binding.setData(data);
...

Reason your click is not redirecting - Your DataBinding has no issue but it is not attached to the view of Activity.

CodePudding user response:

Apparently, I have made a silly mistake here

In SecondActivity.java -

on second line it should be -

private ActivitySecondBinding binding

rather than

private ActivityMainBinding binding

  • Related