【发布时间】:2017-11-02 18:18:03
【问题描述】:
我刚刚在 android spinner 中进行试验,遇到了这个奇怪的应用程序崩溃问题。
这是我默认使用的引用包含方法的类: sr.setOnItemSelectedListener(this); 这很好用
但是当我改变引用这个的方法时:
sr.setOnItemSelectedListener(new MainActivity());
编辑:
我们为什么要通过这个
为什么我们不能通过 new MainActivity() ?
如果使用 Toast,则会引发此错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a android.content.ContextWrapper.getResources(ContextWrapper.java:86) 处的空对象引用
完整代码:
package com.example.defaultspinner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener
{
Spinner sr;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sr = (Spinner) findViewById(R.id.sp);
String[] days = getResources().getStringArray(R.array.days);
ArrayAdapter<String> ar = new ArrayAdapter<>(this, R.layout.single_row, days);
sr.setAdapter(ar);
sr.setOnItemSelectedListener(new MainActivity()); //passing new MainActivity() instead of this (it may be the problem)
System.out.println("THIS -> " + this); //com.example.defaultspinner.MainActivity@3b90554d
System.out.println("NEW -> " + new MainActivity()); //com.example.defaultspinner.MainActivity@1475b903
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String tm = "VALUE -> " + parent.getItemAtPosition(position);
System.out.println("THIS-> " + MainActivity.this); //out -> com.example.defaultspinner.MainActivity@210b457b
System.out.println("APP -> " + getApplicationContext()); //out -> null
System.out.println(tm);
Toast.makeText(MainActivity.this, tm, Toast.LENGTH_LONG).show(); //error is thrown here
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
System.out.println(parent);
}
}
java.lang.NullPointerException:尝试在 android.content.ContextWrapper.getResources(ContextWrapper.java: 86)
如果使用 this 而不是 new Object(),则此程序可以正常工作。
我尝试了以下上下文方法:
Toast.makeText(this, tm, Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, tm, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), tm, Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), tm, Toast.LENGTH_LONG).show();
【问题讨论】:
-
你不能实例化一个Activity的实例。
-
传递一个 this 而不是 new MainActivity
-
问题是
new MainActivity()。将this传递为ItemSelectedListener -
@MuratK。 this 和 new MainActivity() 不一样?
-
不一样的...