首页 \ 问答 \ setOnClickListener导致“RuntimeException:无法启动” - NullPointerException(setOnClickListener is causing “RuntimeException: Unable to start” - NullPointerException)

setOnClickListener导致“RuntimeException:无法启动” - NullPointerException(setOnClickListener is causing “RuntimeException: Unable to start” - NullPointerException)

我收到了一个错误,我无法理解是什么导致了它。

这是生成错误的代码片段:

public class RssReader extends Activity {
private Button button1;
@Override
public void onCreate(Bundle savedInstanceState) {
    button1 = (Button) findViewById(R.id.b1);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("test");
        }
      });

    super.onCreate(savedInstanceState);
    setContentView(R.layout.rss_reader);
    }
}

虽然这是我的rss_reader.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

</LinearLayout>

上面的代码导致NullPointerException ,但我无法理解我正在访问的是什么空指针,因为我没有使用任何不安全的构造。 完整的错误如下:

04-14 18:50:14.305: E/AndroidRuntime(443): FATAL EXCEPTION: main
04-14 18:50:14.305: E/AndroidRuntime(443): java.lang.RuntimeException: Unable to start              activity ComponentInfo{com.cris96.rssreader/com.cris96.rssreader.RssReader}:  java.lang.NullPointerException
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.os.Looper.loop(Looper.java:123)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.main(ActivityThread.java:3683)
04-14 18:50:14.305: E/AndroidRuntime(443):  at java.lang.reflect.Method.invokeNative(Native Method)
04-14 18:50:14.305: E/AndroidRuntime(443):  at java.lang.reflect.Method.invoke(Method.java:507)
04-14 18:50:14.305: E/AndroidRuntime(443):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-14 18:50:14.305: E/AndroidRuntime(443):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-14 18:50:14.305: E/AndroidRuntime(443):  at dalvik.system.NativeStart.main(Native Method)
04-14 18:50:14.305: E/AndroidRuntime(443): Caused by: java.lang.NullPointerException
04-14 18:50:14.305: E/AndroidRuntime(443):  at com.cris96.rssreader.RssReader.onCreate(RssReader.java:14)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-14 18:50:14.305: E/AndroidRuntime(443):  ... 11 more

我该如何解决?

谢谢


I got an error, and I can't understand what's causing it.

This is the snippet of code that generates the error:

public class RssReader extends Activity {
private Button button1;
@Override
public void onCreate(Bundle savedInstanceState) {
    button1 = (Button) findViewById(R.id.b1);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("test");
        }
      });

    super.onCreate(savedInstanceState);
    setContentView(R.layout.rss_reader);
    }
}

while this is my rss_reader.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

</LinearLayout>

The above code is causing a NullPointerException, but I can't understand what null pointer I'm accessing, since I'm not using any unsafe construct. The complete error is the following:

04-14 18:50:14.305: E/AndroidRuntime(443): FATAL EXCEPTION: main
04-14 18:50:14.305: E/AndroidRuntime(443): java.lang.RuntimeException: Unable to start              activity ComponentInfo{com.cris96.rssreader/com.cris96.rssreader.RssReader}:  java.lang.NullPointerException
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.os.Looper.loop(Looper.java:123)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.main(ActivityThread.java:3683)
04-14 18:50:14.305: E/AndroidRuntime(443):  at java.lang.reflect.Method.invokeNative(Native Method)
04-14 18:50:14.305: E/AndroidRuntime(443):  at java.lang.reflect.Method.invoke(Method.java:507)
04-14 18:50:14.305: E/AndroidRuntime(443):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-14 18:50:14.305: E/AndroidRuntime(443):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-14 18:50:14.305: E/AndroidRuntime(443):  at dalvik.system.NativeStart.main(Native Method)
04-14 18:50:14.305: E/AndroidRuntime(443): Caused by: java.lang.NullPointerException
04-14 18:50:14.305: E/AndroidRuntime(443):  at com.cris96.rssreader.RssReader.onCreate(RssReader.java:14)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-14 18:50:14.305: E/AndroidRuntime(443):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-14 18:50:14.305: E/AndroidRuntime(443):  ... 11 more

How can I fix it?

Thank you


原文:https://stackoverflow.com/questions/16003121
更新时间:2022-10-24 12:10

最满意答案

主要原因是VB中的DirectCastas操作符更像C# (cast)操作符。 C#代码的工作原理是asTestDerived不是TestBase<T> (这是任何时候T不是TestItem ),只会返回null 。 如果TestDerived不是TestBase(Of T)DirectCast实际上会失败,所以你会看到错误。

通过使用Typeof Is构造或使用TryCast() ,可以在VB中获得类似的功能。

或者,你可以让TestDerived实际上继承自TestBase<T> ,(因此使TestDerived<T> ),这将使一切工作,而不用两种语言铸造。


The main reason is that DirectCast in VB is much more like the C# (cast) operator than the as operator. The C# code works because as will just return null when TestDerived isn't a TestBase<T> (which is any time T isn't TestItem). DirectCast will actually fail if TestDerived isn't a TestBase(Of T), and so you see the error.

You can get similar functionality in VB by using the Typeof Is construct, or using TryCast().

Alternatively, you could have TestDerived actually inherit from TestBase<T>, (thus making TestDerived<T>) which would make everything work without casting in both languages.

相关问答

更多
  • 基本上与其他Visual Basic代码相同,但我会使用这个机会添加一些样式: Dim value = 20 ' Type inference, like "var" in C# Dim parameters() As Object ' Could also be "parameters As Object()" If value > 10 Then parameters = New Object(19) {} ' That's right, Visual B ...
  • C#LINQ查询语法越接近,将显式object指定为范围变量p类型。 我也不知道VB.NET,但是在C#中select是必需的(只有当最后一个运算符group by w / o into子句时才可以跳过): var items = from object p in ListTest select p; 参考: 如何:使用LINQ(C#) 查询ArrayList如何:使用LINQ查询ArrayList(Visual Basic) The closer C# LINQ query syntax is to s ...
  • 编译的.Net DLL与语言无关:您可以使用任何.Net语言编写的任何.Net语言的DLL。 请注意,一般情况下,您只能引用为.Net或更低版本的.Net编译的.Net DLL(.Net程序集),而不是您设置的目标.Net版本的代码。 理想情况下,DLL(在NuGet和VB.Net中)都针对相同的.Net版本,否则请阅读MSDN:.NET Framework中的版本兼容性 。 A compiled .Net DLL is language agnostic: you can use a DLL writte ...
  • 好的,稍后尝试和讨论它的工作时间。 我做了什么: 我将.net 4.5更改为.net 4.0 我将编译器设置从“AnyCPU”更改为“x86” ' SetupPath() '中的第一行是: System.Environment.SetEnvironmentVariable("R_HOME", "C:\Program Files\R\R-3.0.2") Ok, hours of trying and discussion later it works. What I did: I changed .net 4 ...
  • _字符是VB中的行继续。 尝试将变量名称更改为更常见的名称,例如x For Each msg In SelectedFolder.Search("ALL", True).OrderByDescending(Function(x) x.[Date]).ToList() The _ character is a line continuation in VB. Try changing the variable name to something more common, like x For Each ms ...
  • 主要原因是VB中的DirectCast比as操作符更像C# (cast)操作符。 C#代码的工作原理是as当TestDerived不是TestBase (这是任何时候T不是TestItem ),只会返回null 。 如果TestDerived不是TestBase(Of T) , DirectCast实际上会失败,所以你会看到错误。 通过使用Typeof Is构造或使用TryCast() ,可以在VB中获得类似的功能。 或者,你可以让TestDerived实际上继承自TestBase ,(因此使T ...
  • 如果要手动绑定事件,请尝试使用AddHandler : AddHandler Me.mGrid.RowDataBound, AddressOf RowDataBoundHandler 或者您可以在ASPX标记中绑定事件: 或者使用Tim Schmelter的方法。 Try using AddHandler if you want to bind the event ...
  • 你可能想要Dim serviceWrapper As New而不是Dim serviceWrapper = New那里。 VB.NET通常比C#更明确,特别是Option Infer Off和Option Strict On 。 尝试在源文件的顶部设置它们。 开始明确地向您的语句添加类型,查看错误何时消失。 在应用这些代码后,您可能还会注意到代码其他部分的问题。 但是,修复它们可以帮助您避免运行时出现问题。 You probably want Dim serviceWrapper As New instea ...
  • 实际上,你不能使用T.whatever和泛型; 仅可以采用T 实例方法(基于T的已知约束)。 也许是这样的: // return object since SQL parameter packing static object Parse(string value) { if (string.IsNullOrEmpty(value)) return DBNull.Value; // for SQL parameter return TypeDescriptor.GetConverter ...
  • 你可能不得不施展 : 与仅从单个基本类型派生的其他类型不同, 接口可以从多个基本接口派生。 因此,接口可以从不同的基接口继承同名的类型成员 。 在这种情况下,乘法继承的名称在派生接口中不可用,并且通过派生接口引用任何这些类型成员会导致编译时错误,无论签名或重载如何。 相反,必须通过基接口名称引用冲突类型成员。 You're probably going to have to cast: Unlike other types, which only derive from a single base type ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)