草庐IT

android - 为什么 (ListView)findViewById 返回 null?

coder 2023-12-08 原文

帮助!我真的很欣赏 Stack Overflow 和它在过去几个月里的贡献者。我有很多问题,我在这里找到了答案......但是这个我似乎无法在任何地方找到......我是 Java 和 Android 的菜鸟,我一直在努力弄清楚这个出去几天。出于某种原因,我有一个名为 fileList 的 ListView 对象,它返回 null ...一切都编译得很好,但是当我尝试使用 fileList 时我得到了一个 NullPointerException ...我已经能够将它隔离到它的声明中:

ListView fileList = (ListView)findViewById(R.id.open_ListView);

但我终究无法理解这行代码有什么问题!我在下面包含了很多代码,理论上它应该包含可能以任何方式与此错误相关的所有代码。

如有任何帮助,我们将不胜感激!谢谢!


这是有问题的代码部分。它只是开关 block 的 OPEN_DIALOG 部分,所有其他开关都可以很好地显示它们的新对话框。我已经用星标标记了违规行...

@Override
protected Dialog onCreateDialog(int id) 
{
    Dialog newDialog = new Dialog(Minervalia.this);
    switch(id)
    {
    case DIALOG_FILE_NEW:
        newDialog.setContentView(R.layout.new_file);
        newDialog.setTitle("New File");
        newDialog.setCancelable(true);

        Button okBtn = (Button) newDialog.findViewById(R.id.ok_btn);
        Button cancelBtn = (Button) newDialog.findViewById(R.id.cancel_btn);
        final EditText widthEt = (EditText) newDialog.findViewById(R.id.width_edit);
        final EditText heightEt = (EditText) newDialog.findViewById(R.id.height_edit);

        okBtn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                file_width = Integer.parseInt(widthEt.getText().toString());
                file_height = Integer.parseInt(heightEt.getText().toString());
                onCreate(null);
                dismissDialog(DIALOG_FILE_NEW);
            }
        });

        cancelBtn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dismissDialog(DIALOG_FILE_NEW);
            }
        });
        return newDialog;
    case DIALOG_OPEN:
        newDialog.setContentView(R.layout.open_file);
        newDialog.setTitle("Open File");
        newDialog.setCancelable(true);

// ********** This next line returns null! Why?
        ListView fileList = (ListView)findViewById(R.id.open_ListView);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, loadFileList());
        fileList.setAdapter(adapter);
        fileList.setTextFilterEnabled(true);

        fileList.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {
                //  When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
            }
        });

        return newDialog;
    case DIALOG_SAVE:
        newDialog.setContentView(R.layout.save_file);
        newDialog.setTitle("Save File");
        newDialog.setCancelable(true);

//--==[[ Define the important TextViews for our Save Dialog ]]==--\\            
        TextView pathTxt = (TextView) newDialog.findViewById(R.id.save_path_info);
        EditText fnTxt = (EditText) newDialog.findViewById(R.id.save_filename_edit);

//--==[[ Define the Radio Buttons for our Save Dialog ]]==--\\          
        RadioButton JPEGoption = (RadioButton) newDialog.findViewById(R.id.save_JPEGoption);
        RadioButton PNGoption = (RadioButton) newDialog.findViewById(R.id.save_PNGoption);

        file_type = TYPE_JPEG; // Set this as the default option

        JPEGoption.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                file_type = TYPE_JPEG;
            }
        });

        PNGoption.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                file_type = TYPE_PNG;
            }
        });

        Button save_okBtn = (Button) newDialog.findViewById(R.id.save_ok_btn);
        Button save_cancelBtn = (Button) newDialog.findViewById(R.id.save_cancel_btn);

        path = pathTxt.getText().toString();

        fnTxt.addTextChangedListener(new TextWatcher() 
        { 
            public void afterTextChanged(Editable s) 
            { 
            } 
            public void beforeTextChanged(CharSequence s, int start, int count, int after) 
            { 
            } 
            public void onTextChanged(CharSequence s, int start, int before, int count) 
            { 
                filename = s.toString(); 
            } 
        }); 
        Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, filename, Toast.LENGTH_SHORT).show();
        save_okBtn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try 
                {
                    String fullName = path + filename;
                    Bitmap.CompressFormat compForm = Bitmap.CompressFormat.JPEG; // make sure our format is initialized
                    if(file_type == TYPE_JPEG) 
                    {
                        fullName = fullName + ".jpg";
                        compForm = Bitmap.CompressFormat.JPEG;
                    }
                    if(file_type == TYPE_PNG)
                    {
                        fullName = fullName + ".png";
                        compForm = Bitmap.CompressFormat.PNG;
                    }
                    File thisImage = new File(fullName);
                    FileOutputStream out = new FileOutputStream(thisImage);
                    mBitmap.compress(compForm, 90, out);

                    new SingleMediaScanner(mContext, thisImage);
                    out.flush();
                    out.close();
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }

                dismissDialog(DIALOG_SAVE);
            }
        });

        save_cancelBtn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dismissDialog(DIALOG_SAVE);
            }
        });
        return newDialog;
    }
    return null;
}

private String[] loadFileList()
{
    String[] mFileList = new String[0]; // generate empty array to avoid NullPointerException
    try
    {
        filePath.canWrite();
    }
    catch(SecurityException e)
    {
// Why isn't TAG recognized?...
//           Log.e(TAG, "unable to write on the sd card " + e.toString());
    }
    if(filePath.exists())
    {
        FilenameFilter filter = new FilenameFilter()
        {
            public boolean accept(File dir, String filename)
            {
                File sel = new File(dir, filename);
                return filename.contains(".jpg") || filename.contains(".png") || sel.isDirectory();
            }
        };
        mFileList = filePath.list(filter);
    }
    else
    {
        mFileList = new String[0];
    }
    return mFileList;
}

这是我的 open_file.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView 
        android:id="@+id/open_ListView" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content">
    </ListView>
    <LinearLayout
        android:id="@+id/open_ButtonLinearLayout"
        android:orientation="horizontal" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <Button 
            android:id="@+id/open_ok_btn"
            android:text="Open" 
            android:layout_width="150dp" 
            android:layout_height="wrap_content">
        </Button>       
        <Button 
            android:id="@+id/open_cancel_btn" 
            android:text="Cancel"
            android:layout_width="150dp" 
            android:layout_height="wrap_content">
        </Button>       
    </LinearLayout>
</LinearLayout>

这是我的 list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

最佳答案

试试这个,因为它在对话框的布局内,而不是 Activity 的布局内:

ListView fileList = (ListView)newDialog.findViewById(R.id.open_ListView);

关于android - 为什么 (ListView)findViewById 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6168113/

有关android - 为什么 (ListView)findViewById 返回 null?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  6. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  7. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  8. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  9. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  10. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

随机推荐