开发者

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 AdapterV开发者_Python百科iew.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


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.


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


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.


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

MyApplication.getSomeVariable();

should work just like any other class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜