Spinner在OnClick中返回NullPointerException

时间:2013-04-12 19:34:16

标签: android

我有一个由字符串数组中的值填充的微调器。我可以通过LogCat从微调器中获得完美的值,但是当我尝试获取包含onClick方法的内部类中的值时,LogCat不会显示值或任何消息。我正在尝试将微调器的值添加到我的帮助器中,但它会返回NullPointerException。我不太清楚为什么,我提供了一个LogCat截图和我正在使用的代码。非常感谢所有帮助!

截图: enter image description here

package com.example.weatherapplication;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddCity extends Activity {
EditText name, country;
Button add;
String textSpin;
Spinner sp;

// ISOCodes - this took forever!
String[] ISOCODES = new String[] { "GB", "US" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addcity);

    name = (EditText) findViewById(R.id.name);
    add = (Button) findViewById(R.id.add);
    sp = (Spinner) findViewById(R.id.countryList);

    // populate spinner with ISOCODES
    sp.setAdapter(new ArrayAdapter<String>(this,
             android.R.layout.simple_spinner_item, ISOCODES));

    textSpin = sp.getSelectedItem().toString();

    add.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (name.getText().toString().matches("") || country.getText().toString().matches("")) {
                Toast.makeText(AddCity.this , "Field can't be empty" , Toast.LENGTH_SHORT).show();
            } else {
                DataBaseHelper helper = new DataBaseHelper(AddCity.this);
                helper.openDataBase();
                Log.w("Spinner value two:", textSpin);
                helper.insert(name.getText().toString(), textSpin, R.drawable.red_bg);
                helper.close();
                finish();
            }
        }
    });
  }
}

2 个答案:

答案 0 :(得分:1)

您需要初始化country

name = (EditText) findViewById(R.id.name);
add = (Button) findViewById(R.id.add);
sp = (Spinner) findViewById(R.id.countryList);
country = (/* Appropriate Cast */)findViewById(/* Appropriate resource ID */)

答案 1 :(得分:0)

1)检查是否已正确初始化namecountry字段

2)以这种方式检查它们是否为空:

if (TextUtils.isEmpty(name.getText().toString()) || TextUtils.isEmpty(country.getText().toString()) {
    Toast.makeText(AddCity.this , "Field can't be empty" , Toast.LENGTH_SHORT).show();
} 

使用.matches()进行检查的方式如果为空,可能会导致NullPointerException