Android error java.lang.NullPointerException: Try to invoke virtual Method 'void android.widget.Lis



我正在尝试构建一个简单的列表视图应用程序,但我不断收到这个烦人的错误。我对Android相当陌生,所以我真的不知道如何修复它。任何帮助,不胜感激。

错误行位于 BirthdayReminderActivity.java:

listView.setOnItemClickListener(new OnItemClickListener() {

日志猫错误输出为:

   --------- 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.

生日提醒活动.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());
       }
     }
   }

生日提醒活动.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>

清单.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>

自定义光标适配器生日.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))));
   }
}

生日数据库助手.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
        }
     }
  }

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

我怀疑这条线是BirthdayReminderActivity.java的问题:

setContentView(R.layout.activity_birthday_reminder);

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

setContentView(R.layout.birthdayreminderactivity);

您正在使用线性布局的 id 而不是布局文件名来设置内容视图

 setContentView(R.layout.birthdayreminderactivity);

相关内容

最新更新