不能'将项目添加到Spinner中

时间:2011-06-17 00:31:37

标签: android nullpointerexception spinner add runtimeexception

我正在尝试将一个列表添加到Spinner中,但我总是在LogCat中得到一个例外:

"java.lang.RuntimeException: Unable to start activity ComponentInfo{....}: java.lang.NullPointerException"

在模拟器中,出现一个对话框,说应用程序意外停止,我需要强制关闭。我尝试了不同的东西,但我仍然得到同样的例外。

以下是活动的代码:

public class CreateListActivity extends Activity implements OnClickListener{

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState)
{   
    Spinner categorySpinner = (Spinner)findViewById(R.id.category_Spinner);

    CategoryAction categoryAction = new CategoryAction(getBaseContext());
    ArrayList<ListCategory> categorylist = new ArrayList<ListCategory>();
    ArrayList<String> categoryNames = new ArrayList<String>();

    //Get all existing categories.
    try
    {
        categorylist = (ArrayList<ListCategory>) categoryAction.getAllCategories();
    }

    catch(SQLException e) 
    {
        e.printStackTrace();
    }       

    // Add all existing category names. This will be used to add options to the spinner.
    for (ListCategory category : categorylist)
    {
        categoryNames.add(category.getCategoryName());
    }


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_spinner_item, categoryNames);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.createlist);

    categorySpinner.setAdapter(adapter);    

    View addNewListButton = findViewById(R.id.Add_List_button);
    addNewListButton.setOnClickListener(this);
}

public void onClick(View v) 
{
    ListAction listAction = new ListAction(getBaseContext());

    EditText listEditText = (EditText)findViewById(R.id.listName);
    String newListName = listEditText.getText().toString();

    try {
        if(!listAction.listExist(newListName)){
            listAction.createList(newListName, "To Buy");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    Intent viewListsIntent = new Intent(this, ItemListActivity.class);
    startActivity(viewListsIntent);
}

}

2 个答案:

答案 0 :(得分:0)

您的问题可能与微调器无关。在logcat中,向下滚动一下,将指示出现空指针异常的行。然后修复那个空指针错误。

答案 1 :(得分:0)

在设置视图内容之前,您无法调用findViewById 。你必须移动这些行

  super.onCreate(savedInstanceState);
  setContentView(R.layout.createlist);

onCreate方法的顶部。您可能认为它与Spinners有关,因为您在这两行之前添加了Spinner代码。