TJ1
TJ1

Reputation: 8468

Android passing variables between activities

I want to pass one or more variables between activities in android. One solution is to use global variables, and it is explained here: Android global variable which I repeat here:


You can extend the base android.app.Application class and add member variables like so:

public class MyApplication extends Application {

private String someVariable;

public String getSomeVariable() {
    return someVariable;
}

public void setSomeVariable(String someVariable) {
    this.someVariable = someVariable;
}
}

Then in your activities you can get and set the variable like so:

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();

I want to use this and set a global variable in one of my activities when an item on a ListView is pressed. So I have this code:

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          .
          .
          .

          ((MyApplication) this.getApplication()).setSomeVariable("foo");
        }

      });

However I get an error which says "The method getApplication() is undefined for the type new AdapterView.OnItemClickListener(){}".

I would like to know what is the reason I get this error and how to fix it, or a better way of passing a variable from one activity to the other.

Thanks,

TJ

Upvotes: 1

Views: 10690

Answers (4)

Michele
Michele

Reputation: 6131

Inside an Anonymous Class you cant say this. u have to specifi the Class around the inner class.

like MyApplication.this.get..

when using:

class MyApplication { 
  lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          ((MyApplication) MyApplication.this.getApplication()).setSomeVariable("foo");
        }
 }

}

the "this." inside an annoymous inner class refering to the inner class itself.

Upvotes: 4

source.rar
source.rar

Reputation: 8080

Any particular reason you are not using Intent's? http://developer.android.com/guide/topics/fundamentals/activities.html#StartingAnActivity

Upvotes: 1

rf43
rf43

Reputation: 4405

I don't think you need to cast it... Application is already there.

MyApplication.getSomeVariable();

should work just like any other class.

Upvotes: 0

P.Melch
P.Melch

Reputation: 8180

You have the use MyClass.this.getApplication() if you've define the anonymous OnItemClickListener in a member function of MyClass. OnItemClickListener does not know about the application.

Upvotes: 0

Related Questions