1

I have a main activity class and find class. I need to access variable of main activity variable's that is "name" from find class. I tried to access with below snippet code but I get an error. How can I access main activity variables from another class ?

public class main extends Activity {

     public static String name=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button1=(Button)findViewById(R.id.button1);

        final EditText edittext = (EditText) findViewById(R.id.editText1);

        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                name=edittext.getText().toString();

            }
        });                                                
}

My second class....

public class find {

public void finder(){

    main mainactivity=new main();
    String incoming_name =mainactivity.name;//I can not use like that ? 
            // do something 
}

}

Co Koder
  • 2,021
  • 7
  • 31
  • 39

2 Answers2

8

1) You shouldn't instantiate an activity, intents start activities

2) You have declared the variable public static, so you can simply reference it (without instantiating the class) by main.name...

Barak
  • 16,318
  • 9
  • 52
  • 84
4

You don't want to access Activity's variables directly from another (outer) class. This is a bad practice, as Activities are, after all, part of the UI, and not the backend of the application.

Also, note that in your example, the name property is static and doesn;t belong to a specific instance.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • So, how can I get the value of edittext in this case ? – Co Koder May 13 '12 at 01:11
  • This requires to know the relation between the classes and the purpose of finder. – MByD May 13 '12 at 01:13
  • @MByD My purpose is that I have a flag in my activity and I want to update it from fragment, after user goes through some processes. What is the proper way to update a variable in activity? – Gokhan Arik Apr 06 '15 at 17:20