Search code examples
javaandroidexceptionnullpoint

Need help to spot null pointer exception java


When i compile this to my android device it gives me a null pointer exception. i have been trying to find where the null pointer exception is, but without any luck. i have an activity with a button and an edittext. When you click the button the text in the edittext should end up as an item in a listview. Please help.

log: http://i61.tinypic.com/14lq33n.jpg

Source:

package com.example.foodplannerbeta;

import java.util.ArrayList;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class Indkob2Activity extends Activity {

private Button bt;
private ListView lv;
private ArrayList<String> al;
private ArrayAdapter<String> adapter;
private EditText et;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_indkob2);

    bt = (Button) findViewById(R.id.btncustomindkob);
    lv = (ListView) findViewById(R.id.listView1);
    et = (EditText) findViewById(R.id.customEdittrec);
    al = new ArrayList<String>();

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al);
    lv.setAdapter(adapter);
    bt.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            al.add(et.getText().toString());
            adapter.notifyDataSetChanged();
        }
    });


   }
}

Solution

  • The NPE seems to be on the bt.setOnClickListener() call. That is, bt is null.

    Make sure your activity_indkob2 layout in fact contains a view with id btncustomindkob.