Android ImageView变量即使在定义后仍返回null;安卓

Android ImageView变量即使在定义后仍返回null;安卓,android,Android,在我的程序中,我试图使用ImageView显示文件中的图像。我已声明ImageView与ImageView XML文件相关,并已使用BitmapFactory将该值设置为文件中的图像。在所有这些之后,我仍然收到一个NullPointerException,因为ImageView变量显然仍然为null。如果你有任何想法或建议,请让我知道,谢谢 下面是我要说的代码: public void imageViewMethod(String file){ Logger log = Logger.g

在我的程序中,我试图使用ImageView显示文件中的图像。我已声明ImageView与ImageView XML文件相关,并已使用BitmapFactory将该值设置为文件中的图像。在所有这些之后,我仍然收到一个NullPointerException,因为ImageView变量显然仍然为null。如果你有任何想法或建议,请让我知道,谢谢

下面是我要说的代码:

public void imageViewMethod(String file){
    Logger log = Logger.getLogger("com.example.myclass");

    try {

    File fileName = new File(root, file);
    if(fileName.exists()){
    String dirFileName = fileName.toString();
    Toast.makeText(getApplicationContext(), dirFileName, Toast.LENGTH_LONG).show();
    ImageView iv = (ImageView)findViewById(R.id.image);

    iv.setImageBitmap(BitmapFactory.decodeFile(dirFileName));
    super.setContentView(iv);
    }
    }catch(Exception e){
        Toast.makeText(getApplicationContext(), "Hit Exception", Toast.LENGTH_LONG).show();
        log.log(Level.SEVERE, "uncaught exception", e);
    }
}
以及相应的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 

android:layout_margin="5dp">
</ImageView>

您是否正确设置了
contentView()
?您似乎使用了
super.setContentView(iv)在错误的位置
setContentView(R.layout.imageviewLayout.xml)
用于activity类的
onCreate()

检查活动类中是否有以下代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageviewLayout.xml);

HTH.

看来您还没有在oncreate中设置ContentView,您必须在获取ImageView之前设置ContentView

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.correspondingXML);

设置contentview之前无法获取imageview。

如果要在活动运行时更改布局,请尝试使用LayoutInflater:

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.image_layout, null);
setContentView(view);

现在
findViewById(R.id.image)
将起作用。

我没有在onCreate中设置ContentView的原因是,最初的显示是一个包含文件名的列表视图。选择文件名后,将打开此方法以尝试显示图像。也许我应该使用意图并开始一项新的活动?还有其他想法吗?好的,那么您当前的活动没有像contentview那样的xml列表?是的,当前活动有一个列表适配器来显示文件名。然后在onItemClick方法中,我检索被按下的文件名并调用'imageViewMethod(f2);'-如果f2是文件名。那么是的,不需要创建新的活动并将内容视图设置为image.xml,然后将获得Imageview,并且必须在此处通过文件名之类的意图传递数据……。非常感谢,我感谢您的帮助!