2013-03-27 91 views
1

我查看了很多帖子并尝试了它们,但似乎没有任何效果。我想这可能是我错过的东西。这是我想要做的和我的问题:我试图创建一个全局变量,以便在我的主要活动中,当用户从ListView中选择一个项目时,我想将该项目分配给该变量,通过我的应用程序使用它。创建全局变量,并在OnClickListener中设置变量时出现错误ListView

杉杉我创建了一个类,并将其延伸到像后续的应用:

进口android.app.Application;

公共类GlobalVariables扩展应用{

private String mStringValue; 

public String getSomeVariable() { 
    return mStringValue; 
} 

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

}

然后在我的主要活动,我把这个这个代码来设置变量:

public class MainActivity extends Activity {  

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);  


ListView.setOnItemClickListener(new OnItemClickListener() {  

@Override 
public void onItemClick(AdapterView<?> listView, View view,  
int position, long id) {  

// Get the cursor, positioned to the corresponding row in the result set  
Cursor cursor = (Cursor) listView.getItemAtPosition(position);  
// Get the Customer Name from this row in the database.  
String countryCode = cursor.getString(cursor.getColumnIndexOrThrow("CustomerName"));  

Toast.makeText(getApplicationContext(), countryCode, Toast.LENGTH_SHORT).show();  

((GlobalVariables) this.getApplication()).setSomeVariable(countryCode); 

    } 

}); 

的问题是我出现错误“该方法的getApplication()方法未定义为类型new AdapterView.OnItemClickListener(){}”:

((GlobalVariables) this.getApplication()).setSomeVariable(countryCode); 

我阅读后的一个建议做如下的代码,但后来我得到另一个多个错误:

  • 方法getApplication()是未定义的类型GlobalVariables
  • 没有封闭GlobalVariables类型的实例可在范围内访问

    ((GlobalVariables)GlobalVariables.this.getApplication())。setSomeVariable(“foo”);

任何帮助,你可以给我将不胜感激。

谢谢

回答

0

OnItemClickListener()是一个匿名内部类。这意味着当你在里面this时,this实际上是指OnItemClickListener类型的对象,它没有方法getApplication()

尝试:

((GlobalVariables) MainActivity.this.getApplication()).setSomeVariable(countryCode); 
+0

谢谢你的帮助 – user2105000 2013-03-27 19:27:28

0

你为什么不定义GlobalVariables如下:

public class GlobalVariables 
{ 
    static String mStringValue; 
} 

然后你就可以在你的应用程序GlobalVariables.mStringValue在任何地方使用它,例如GlobalVariables.mStringValue = COUNTRYCODE;