为什么我不能在android中为spinner设置值

时间:2014-04-02 01:21:43

标签: android

我有一个Class,当它执行时,会显示以下错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.onth/com.example.onth.Savedlocation}: java.lang.NullPointerException  

这是我的代码:

package com.example.onth;

import java.util.List;
import org.w3c.dom.Comment;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Savedlocation extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DatabaseHandler db = new DatabaseHandler(this);

           Log.d("Reading: ", "Reading all contacts..");
            List<locationprofl> loc = db.getAlllocation();  
            String log = " ";

            for (locationprofl cn : loc) {
                 log ="lat: "+cn.getlat()+" long:"+cn.getlong()+" ,Name: " + cn.getName() + " ,Profile: " + cn.getProfile();
                 Log.v("aaa", log);

            }
            final Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
            String[] items = new String[]{"General", "Silent", "Outdoor"};
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
            dropdown.setAdapter(adapter);
            //addListenerOnButton();    

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.savedlocation, menu);
        return true;
    }

}

3 个答案:

答案 0 :(得分:1)

您没有将内容设置为活动。 (缺少setContentView)。

final Spinner dropdown = (Spinner)findViewById(R.id.spinner1);  

下拉列表将为null,因为您尚未将视图设置为活动

答案 1 :(得分:0)

问题是你的微调器是null。 您需要为此活动设置一个视图,否则findViewById将找不到您的微调器。

setContentView(R.layout.yourLayoutFile);

之后添加super.onCreate(savedInstanceState);

答案 2 :(得分:0)

您忘了拨打setContentView();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location_saved); //You forgot this line
    DatabaseHandler db = new DatabaseHandler(this);
    ...  

}