我剛剛在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();
您無法實例化活動的實例。 –
傳遞這個而不是新的MainActivity –
問題* IS *'新的MainActivity()'。通過'this'作爲'ItemSelectedListener' –