1

文字列配列の値が取り込まれるスピナーがあります。LogCat を介してスピナーから完全に値を取得できますが、onClick メソッドを保持する内部クラス内で値を取得しようとすると、LogCat は値やメッセージをまったく表示しません。スピナーからヘルパーに値を追加しようとしていますが、NullPointerException が返されます。理由はよくわかりませんが、LogCat のスクリーンショットと以下に使用しているコードを提供しました。すべてのヘルプは大歓迎です!

スクリーンショット: ここに画像の説明を入力

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();
            }
        }
    });
  }
}
4

2 に答える 2

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 */)
于 2013-04-12T19:37:01.253 に答える
0

1)フィールドが正しく初期name化されていることを確認しますcountry

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

于 2013-04-12T19:42:42.570 に答える