Search code examples
javaandroidandroid-intentandroid-viewfindviewbyid

Not being able to access my custom view object from another class


I have been trying to find a solution for my problem for quite sometime now but to no avail. I have a customView class that I add statically into my MainActivity's layout (I add it in the XML file). I have a second Activity that needs to have access to my customView's methods as it will retrieve data from it and change some data. However, my second activity needs to only access that same object of the custom view that was already added to the MainActivity.

I want it to look something like this:

In my MainActivity.java I would do this:

public class MainActivity extends AppCompatActivity {


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

    Button btn = (Button) findViewById(R.id.btnID);


    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent btnIntent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(btnIntent);
        }
    });


}   

And in my SecondActivity it would be something like this:

public class SecondActivity extends AppCompatActivity {


 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);


 CustomView viewer = (CustomView) findViewById(R.id.custom); //I want to link to the view I added in the MainActivity

 viewer.getData(); // Example of what methods I want to use here
 viewer.setData(); // It should directly set/get the data from the object in the MainActivity

So far I have tried this:

public static CustomView viewer = (CustomView) findViewById(R.id.custom);

In the MainActivity so that I can then use viewer in the SecondActivity but that didn't work because findViewById is non-static.

I have also tried adding this:

CustomView viewer = (CustomView) ((Activity)context).findViewById(R.id.custom);

In the SecondActivity but then I would get an error that I am invoking findViewById on a null reference.

I am not entirely sure what I can do, I have searched a lot online and in SO but I still can't fix the problem.

I am still a beginner in android so I would be grateful if someone manages to help me out.

Thanks!


Solution

  • This way you can send your extras to another activity from ClassA:

    Intent intent = new Intent(ClassA.this, ClassB.class);
                intent.putExtra("A", "A");
                startActivity(intent);
    

    And receive it at ClassB:

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    
    if (extras != null) {
        if (extras.containsKey("A")) {
            //do your stuff
        }
    }