-2

I have set the EditBox variables in Main class. I want to get the value of the editbox in another class. But return a null value. Where am I doing wrong? Thanks.

public class Main extends Activity{ 
{
EditText name; 
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 
loadInfo(); }

loadInfo()
{
SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        name.setText(preferences.getString("name", ""));
}  

}


public class A
{
 Main m;

String str= m.name.getText().toString(); 
}
1
  • 1
    The code that you posted will not compile because it is completely invalid. Please post your actual code, or a compilable example that fully demonstrates your problem. Jul 15, 2011 at 14:17

3 Answers 3

3

You never instantiate m; you merely create a reference for type Main, and call it m. You have to use:

Main m = new Main();
1
  • He never instantiates name in the Main class, either, for that matter (although the syntax is completely invalid anyway; the example won't compile). Jul 15, 2011 at 14:13
0

you can use Intent if you want pass string from Activity to Activity.

0

inside the activity, name = (EditText) findViewById(R.id.yourEditTextId);

To use the "name"(which is an odd name for an EditText, BTW) inside other classes, you need to have a reference to the Main instance, and you can do this: mainInstance.name.

Although I think it's not a good idea to keep "name" public.
In many places, you can use: findViewById() to get the View, View.getContext(), Adapter.getContext() to get the context, which is the Main instance.(You need to cast if you want to use your own methods.)

I didn't test, but I think you can not instantiate Main in android like this new Main().

Anyway, I suggest you read some basic Android tutorials :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.