Intent(context,Class)不工作当我传入类对象时给出错误

时间:2014-03-14 14:58:08

标签: java android android-intent

我正在开发android。我上了课,我以编程方式创建了一个列表。一切正常,除非我将类对象传递给Intent构造函数,java给出了一个错误,它无法解析变量。

public class HomePageActivity extends ListActivity {

String courses[]= {"MobileComputing", "Professional Issues",
        "Advance Programming", "Network Security", "Final Year Project-1"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(HomePageActivity.this, android.R.layout.simple_list_item_1, courses));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);

    try {
        Class courseOne = Class.forName("com.fastnuces.keepmeposted.courseone");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Intent CourseOneScr = new Intent(HomePageActivity.this, courseOne);
    startActivity(CourseOneScr);
    }

}

1 个答案:

答案 0 :(得分:1)

try/catch之外声明您的变量或将Intent移到其中。

 try {
    Class courseOne = Class.forName("com.fastnuces.keepmeposted.courseone");
    Intent CourseOneScr = new Intent(HomePageActivity.this, courseOne);
    startActivity(CourseOneScr);  
} catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

如果它位于try内,那么如果有exception就会无法访问它,并且它之外的任何内容可能都不会知道它。