开发者

Cant' add items into a Spinner

I'm trying to add a list into a Spinner but I'm always getting an exception in LogCat saying:

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

In the emulator, a dialog comes up saying that the application has stopped unexpectedly and I need to Force Close. I've tried different things, but I'm still getting the same exception.

Here's the code for the Activity:

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 I开发者_C百科ntent(this, ItemListActivity.class);
    startActivity(viewListsIntent);
}

}


Your issue has probably nothing to do with spinners. In the logcat, scroll down a bit and the line where the null pointer exception occurs will be indicated. Then just fix that null pointer bug.


You cannot call findViewById before you set the view contents. You must move these lines

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

to the top of your onCreate method. You probably think it has to do with Spinners because you added the Spinner code before these two lines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜