2017-06-01 50 views
0

我刚刚在android spinner中进行了实验,并且遇到了这个奇怪的应用程序崩溃问题。来自听众使用对象的Android Toast

这是我默认使用的引用包含方法的类: sr.setOnItemSelectedListener(this); 这工作超精细

但是,当我改变引用此方法:
sr.setOnItemSelectedListener(新MainActivity());

编辑
为什么要通过
我们为什么不能传递新MainActivity()

如果吐司使用时引发此错误:
显示java.lang.NullPointerException:尝试一个空对象上调用虚拟方法android.content.res.Resources android.content.Context.getResources()'在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);  //[email protected] 
     System.out.println("NEW -> " + new MainActivity()); //[email protected] 
    } 

    @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 -> [email protected] 
     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.Nu llPointerException:尝试在android.content.ContextWrapper.getResources的空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'(ContextWrapper.java:86)

This程序工作正常,如果被用来代替新的对象()。
我想这些方面如下方法:

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(); 
+0

您无法实例化活动的实例。 –

+0

传递这个而不是新的MainActivity –

+0

问题* IS *'新的MainActivity()'。通过'this'作为'ItemSelectedListener' –

回答

0

您无法自行实例化一个新的活动。您可以处理Activity的生命周期,但不处理由框架处理的实例。然后,当您使用this时,您传递的Activity实例扩展为Context,这就是为什么它在这种情况下工作,而new MainActivity()创建了不同于this的活动的新实例。

希望这会有所帮助。

对不起,我的英语。