Android错误java.lang.NullPointerException:尝试调用虚方法' void android.widget.ListView.setOnItemClickListener

时间:2017-01-06 15:39:01

标签: java android android-layout listview nullpointerexception

我正在尝试构建一个简单的列表视图应用程序,但我不断收到这个恼人的错误。我对Android很新,所以我真的不知道如何修复它。任何帮助表示赞赏。

错误行位于BirthdayReminderActivity.java中:

listView.setOnItemClickListener(new OnItemClickListener(){

Logcat错误输出为:

   --------- beginning of crash
   E/AndroidRuntime: FATAL EXCEPTION: main
              Process: premprakash.birthdayreminder, PID: 2266
              java.lang.RuntimeException: Unable to start activity    ComponentInfo{premprakash.birthdayreminder/premprakash.birthdayreminder.BirthdayReminderActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
                  at premprakash.birthdayreminder.BirthdayReminderActivity.onCreate(BirthdayReminderActivity.java:51)
                  at android.app.Activity.performCreate(Activity.java:6662)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

 Application terminated.

BirthdayReminderActivity.java

package premprakash.birthdayreminder;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Gravity;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import android.widget.AdapterView;

import android.os.Handler;

import android.util.Log;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListView;


public class BirthdayReminderActivity extends AppCompatActivity {

private CustomCursorAdapterBirthday customAdapter;
private BirthdayDatabaseHelper databaseHelper;
private static final int ENTER_BIRTHDAY_REQUEST_CODE = 1;
private ListView listView;

private static final String TAG = BirthdayReminderActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_birthday_reminder);

    Button add = (Button) findViewById(R.id.add);


    databaseHelper = new BirthdayDatabaseHelper(this);

    listView = (ListView) findViewById(R.id.list_birthday);


    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "clicked on item: " + position);
        }
    });

    // Database query can be a time consuming task ..
    // so its safe to call database query in another thread
    // Handler, will handle this stuff for you <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            customAdapter = new CustomCursorAdapterBirthday(BirthdayReminderActivity.this, databaseHelper.getAllBirthday());

            System.out.println("dsafjkdsjflkdsjfkdsjf");
            listView.setAdapter(customAdapter);
        }
    });

}

public void onClickAdd(View add) {

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getApplicationContext(), "Successfully Added", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.show();
            startActivity(new Intent(BirthdayReminderActivity.this, ReminderTypesActivity.class));
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent birthday) {

    super.onActivityResult(requestCode, resultCode, birthday);

    if (requestCode == ENTER_BIRTHDAY_REQUEST_CODE && resultCode == RESULT_OK) {

        databaseHelper.insertBirthday(birthday.getExtras().getString("tag_name"), birthday.getExtras().getString("tag_date"), birthday.getExtras().getString("tag_setalarm"), birthday.getExtras().getString("tag_date1"), birthday.getExtras().getString("tag_time"));

        customAdapter.changeCursor(databaseHelper.getAllBirthday());
       }
     }
   }

birthdayreminderactivity.xml

<?xml version="1.0" encoding="utf-8"?>     

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_birthday_reminder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="premprakash.birthdayreminder.BirthdayReminderActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/add"
    android:visibility="visible"
    android:contextClickable="true"
    tools:text="@string/add"
    android:onClick="onClickAdd"
    tools:ignore="UnusedAttribute" />

<SearchView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/add"
    android:layout_alignTop="@+id/add"
    android:id="@+id/search"
    android:orientation="vertical"
    android:filterTouchesWhenObscured="false"
    android:focusableInTouchMode="true"
    tools:focusableInTouchMode="false"
    android:clickable="true"
    tools:ignore="RtlHardcoded" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="NestedScrolling"
    android:id="@+id/list_birthday"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

 </RelativeLayout>

的manifest.xml

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="premprakash.birthdayreminder">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".BirthdayReminderActivity">
        <intent-filter>
            <action android:name="android.intent.action.BIRTHDAYREMINDER" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".ReminderTypesActivity">
        <intent-filter>
            <action android:name="android.intent.action.REMINDERTYPES" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".BirthdayFormActivity">
        <intent-filter>
            <action android:name="android.intent.action.BIRTHDAYFORM" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".AnniversaryFormActivity">
        <intent-filter>
            <action android:name="android.intent.action.ANNIVERSARYFORM" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".OthersFormActivity">
        <intent-filter>
            <action android:name="android.intent.action.OTHERSFORM" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

CustomCursorAdapterBirthday.java

package premprakash.birthdayreminder;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;


public class CustomCursorAdapterBirthday extends CursorAdapter {

public CustomCursorAdapterBirthday(Context context, Cursor c) {
    super(context, c);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    // when the view will be created for first time,
    // we need to tell the adapters, how each item will look
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View retView = inflater.inflate(R.layout.activity_birthday_reminder, parent, false);

    return retView;
  }

@Override
public void bindView(View view, Context context, Cursor cursor) {
    // here we are setting our data
    // that means, take the data from the cursor and put it in views

    TextView textViewName = (TextView) view.findViewById(R.id.name);
    textViewName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));

    TextView textViewDate = (TextView) view.findViewById(R.id.date);
    textViewDate.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));

    TextView textViewSetalarm = (TextView) view.findViewById(R.id.setalarm);
    textViewSetalarm.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(3))));

    TextView textViewDate1 = (TextView) view.findViewById(R.id.date);
    textViewDate1.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4))));

    TextView textViewTime = (TextView) view.findViewById(R.id.time);
    textViewTime.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5))));

   }
}

BirthdayDatabaseHelper.java

 package premprakash.birthdayreminder;


 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;

 public class BirthdayDatabaseHelper {

 private static final String TAG = BirthdayDatabaseHelper.class.getSimpleName();

 // database configuration
 // if you want the onUpgrade to run then change the database_version
 private static final int DATABASE_VERSION = 4;
 private static final String DATABASE_NAME = "birthdaydatabase.db";

// table configuration
private static final String TABLE_NAME = "birthday";         // Table name
private static final String BIRTHDAY_TABLE_COLUMN_ID = "_id";     // a column named "_id" is required for cursor
private static final String BIRTHDAY_TABLE_COLUMN_NAME = "name";
private static final String BIRTHDAY_TABLE_COLUMN_DATE = "date";
private static final String BIRTHDAY_TABLE_COLUMN_SETALARM = "setalarm";
private static final String BIRTHDAY_TABLE_COLUMN_DATE1 = "date1";
private static final String BIRTHDAY_TABLE_COLUMN_TIME = "time";

private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;

// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public BirthdayDatabaseHelper(Context Context) {

    openHelper = new DatabaseOpenHelper(Context);
    database = openHelper.getWritableDatabase();
 }

 public void insertBirthday (String Name, String Date, String Setalarm, String Date1, String Time) {

    // we are using ContentValues to avoid sql format errors

    ContentValues contentValues = new ContentValues();

    contentValues.put(BIRTHDAY_TABLE_COLUMN_NAME, Name);
    contentValues.put(BIRTHDAY_TABLE_COLUMN_DATE, Date);
    contentValues.put(BIRTHDAY_TABLE_COLUMN_SETALARM, Setalarm);
    contentValues.put(BIRTHDAY_TABLE_COLUMN_DATE1, Date1);
    contentValues.put(BIRTHDAY_TABLE_COLUMN_TIME, Time);

    database.insert(TABLE_NAME, null, contentValues);
  }

  public Cursor getAllBirthday () {

    String buildSQL = "SELECT * FROM " + TABLE_NAME;

    Log.d(TAG, "getAllBirthday SQL: " + buildSQL);

    System.out.println("HKJHDSFKJDhf");

    return database.rawQuery(buildSQL, null);
   }

// this DatabaseOpenHelper class will actually be used to perform database related operation

 private class DatabaseOpenHelper extends SQLiteOpenHelper {

    public DatabaseOpenHelper(Context Context) {
        super(Context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        // Create your tables here

        String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + BIRTHDAY_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " + BIRTHDAY_TABLE_COLUMN_NAME + " TEXT, " + BIRTHDAY_TABLE_COLUMN_DATE + " TEXT, " + BIRTHDAY_TABLE_COLUMN_SETALARM + " TEXT, " + BIRTHDAY_TABLE_COLUMN_DATE1 + " TEXT, " + BIRTHDAY_TABLE_COLUMN_TIME + " TEXT )";

        Log.d(TAG, "onCreate SQL: " + buildSQL);

        sqLiteDatabase.execSQL(buildSQL);
     }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        // Database schema upgrade code goes here

        String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;

        Log.d(TAG, "onUpgrade SQL: " + buildSQL);

        sqLiteDatabase.execSQL(buildSQL);       // drop previous table

        onCreate(sqLiteDatabase);               // create the table from the beginning
        }
     }
  }

2 个答案:

答案 0 :(得分:0)

这是一个标准的空指针异常,即您正在尝试访问不存在的对象。在您的情况下,您的活动无法找到您的ListView,因此findViewById已返回空对象。

我怀疑这一行是BirthdayReminderActivity.java中的问题:

setContentView(R.layout.activity_birthday_reminder);

它与您提供的xml文件(birthdayreminderactivity.xml)的名称不同,因此您的活动正在膨胀名为activity_birthday_reminder的文件。尝试将其更改为:

setContentView(R.layout.birthdayreminderactivity);

答案 1 :(得分:0)

您正在使用linearlayout的ID而不是布局文件名

设置contentview
 setContentView(R.layout.birthdayreminderactivity);