Antonio
Antonio

Reputation: 77

How to use a String outside onCreate method

I have the following code in my onCreate method:

Bundle appleData = getIntent().getExtras();
    if(appleData==null) {
        return;
    }
    String appleMessage = appleData.getString("appleMessage");

    final TextView texttest = (TextView) findViewById(R.id.texttest);
    texttest.setText(appleMessage);

I want to use the string stored in appleMessage in a different method on the same activity that is outside of onCreate, how do I go about doing this?

Upvotes: 1

Views: 1754

Answers (4)

codeMagic
codeMagic

Reputation: 44571

If you need it in several places in the class then you can make it a member variable by declaring it outside of a method

public class SomeClass extends Activity {

    String appleMessage = "default text";

but if you only need it in one method you can simply pass it to the method call if you are calling the method in onCreate()

public void onCreate(Bundle bundle) {
   ...
   String appleMessage = appleData.getString("appleMessage");

   final TextView texttest = (TextView) findViewById(R.id.texttest);
   texttest.setText(appleMessage);

   // here
   myMethod(appleMessage);
}

assuming myMethod takes a String as a parameter.

I also suggest you read the java docs and some basic tutorials before continuing with Android. It will make your life much easier.

Upvotes: 3

Matt d'
Matt d'

Reputation: 137

Create a member variable on the class, which is set inside the onCreate method.

See here for more information on instance/member variables.

So:

class SomeClass extends Activity {
    private String appleMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        appleMessage = ...
    }

    public void otherMethod() {
        Log.e("LOG", "Here is appleMessage: " + appleMessage);
    }
}

Upvotes: 2

cristianorbs
cristianorbs

Reputation: 720

You should declare a String attribute outside of the onCreate method. For example:

private String appleMessage;

Then, inside your onCreate, simply change this line:

appleMessage = appleData.getString("appleMessage");

When you want to use it on other method, just call it. Its value will be the value setted on the onCreated method.

Upvotes: 3

Murat Karagöz
Murat Karagöz

Reputation: 37584

Declare it inside your class and no in the method.

e.g.

private String appleMessage;

and use getters and setters for it

public String getAppleMessage(){
 return appleMessage;
}

Upvotes: 1

Related Questions