有下面代码:功能很简单就是点击图片,自动更换的功能。
public class TdwuActivity extends Activity
{        final ImageView imageView = new ImageView(this);//如果将imageview放在这里会出现问题 static int[] images = new int[]
{ R.drawable.ajax, R.drawable.classic, R.drawable.ee, R.drawable.java };
int currentimage = 0;
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
final ImageView imageView = new ImageView(this);//在这里则没有事情 super.onCreate(savedInstanceState);
setContentView(R.layout.main);
                   LinearLayout layout = (LinearLayout) findViewById(R.id.mysql); layout.addView(imageView);
imageView.setImageResource(images[0]);
imageView.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
imageView.setImageResource(images[currentimage + 1]);
currentimage++;
if (currentimage == 3)
{
currentimage = 0;
} }
}); }
}怎么回事那?抛出的异常是空异常。

解决方案 »

  1.   

    final ImageView imageView = new ImageView(this);//如果将imageview放在这里会出现问题
    把final去掉
      

  2.   

    我是这么理解的,不对勿喷:
    final ImageView imageView = new ImageView(this);这样做时这个this还没构造完成
    变量的初始化在构造方法之前
    而你在onCreate方法力执行
    final ImageView imageView = new ImageView(this);
    就没问题因为此时构造方法已经执行完毕,this已经存在。强烈不建议在声明全局变量的时候就实例化,经验总结。
      

  3.   

    是这样的一段测试的代码,结果为空。
    就是想知道为啥呵呵
    package Text;import java.*;
    import java.awt.TextComponent;
    import java.util.logging.Logger;public class Text extends Father
    {
    TextFather father = new TextFather(this); public Text(String name, String age)
    {
    super(name, age);
    } public static void main(String[] arg)
    {
    Text text = new Text("asda", "asd");
    System.out.print(text.father.b);
    }}class TextFather
    {
    String nameString = null;
    boolean b=true; public TextFather(Text age)
    {
    nameString = age.ageString;
    b = builder(nameString);
    } private boolean builder(String str)
    {
    return str.isEmpty(); }
    }
      

  4.   

    package Text;public class Father
    {String nameString=null;
    String ageString=null;
    public Father(String name,String age)
    {

    nameString=name;
    ageString=age;
    }}
      

  5.   

    imageview的初始化应该放到oncreate里面吧
      

  6.   

    zhlwwj1314说得不大正确。。
    final ImageView imageView = new ImageView(this);这个时候this是绝对存在的,你必须搞清楚类的初始化过程,先父类的成员变量初始化,再父类构造函数,再子类的成员变量,再子类的构造函数。
    但问题就出在这里了。
    出错的代码中,final ImageView imageView = new ImageView(this);是类的成员变量,他的初始化早于构造函数。而onCreate却远远晚于类的构造函数。也就是说,final ImageView imageView = new ImageView(this);这句话执行时,该acitivity还未执行onCreate函数,也就没有指定相应的bundle或者说context。而ImageView的构造函数中,所需要的this,其实是context,而context这个时候却未指定,那么自然就出错了。