2010-11-01 52 views
0

我在名为Table的类中创建了一个名为insertTable的方法,但我无法在主要的onClick方法中使用它类:我在另一个类中创建了一个方法,但是我无法在主类中使用onClick方法

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    DatabaseHelper helper = new DatabaseHelper(this); 
    SQLiteDatabase db = helper.getWritableDatabase(); 
    Table expense = new Table(db,helper.TABLE_1); 
    Table income = new Table(db,helper.TABLE_2); 
    Button add_btn = (Button)findViewById(R.id.add_btn); 
    EditText add = (EditText)findViewById(R.id.add); 
    add_btn.setOnClickListener(this); 
} 

public void onClick(View v) { 

} 

我想在onClick方法做一个income.insertTable但eclipse说我需要创建一个局部变量。 有人可以帮我吗?

回答

0

你必须让 “收入” 的实例变量,就像这样:

public class Main { 
    private Table income; 

    //... 
} 

和改变这一行:

Table income = new Table(db,helper.TABLE_2); 

这样:

income = new Table(db,helper.TABLE_2); 

您应该检查关于变量示波器的信息,请参阅此资源: http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

+0

好的谢谢我没有想到这一点。 – Tsunaze 2010-11-01 17:08:03

0

变量incomeonClick()方法中不存在,因为您将其声明为onCreate()的本地方法。 onClick()是在variable's scope之外。最简单的办法是使income“全球”整体活动的类:

public class MyClass extends Activity { 
    private Table income; 
    //Some other stuff here 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     DatabaseHelper helper = new DatabaseHelper(this); 
     SQLiteDatabase db = helper.getWritableDatabase(); 
     Table expense = new Table(db,helper.TABLE_1); 

     // Notice how this next line has changed; you don't 
     // need to specify the type of income since it's 
     // already been declared 
     income = new Table(db,helper.TABLE_2); 
     Button add_btn = (Button)findViewById(R.id.add_btn); 
     EditText add = (EditText)findViewById(R.id.add); 
     add_btn.setOnClickListener(this); 
    } 

    public void onClick(View v) { 
     income.insertTable(someTable); 
    } 
} 

你可以与你在onCreate()创建以及对象的其余做到这一点。

+0

谢谢,哇,stackoverflow真的很快=) – Tsunaze 2010-11-01 17:08:26

0

以上答案是正确的。我只想在Android范例中添加你将要使用Field变量的功能。我发现重构的局部变量为有效地ecilpse领域最好的办法是:

键盘快捷键 选择局部变量 按住Shift + Alt + T,V

菜单 选择局部变量 重构=>将本地变量转换为字段... =>确定

相关问题