始终错误"空指针异常"在ListView Android Studio上

时间:2015-11-01 06:32:58

标签: java android listview android-listview

这里我想创建一个包含listview的应用程序。 我已经定义了使用此列表视图所需的所有内容,但我不知道为什么,当我运行应用程序时,我收到了此错误报告:

  

处理:com.gook.ever_ncn.cashflow,PID:11882       java.lang.RuntimeException:无法启动活动ComponentInfo {com.gook.ever_ncn.cashflow / com.gook.ever_ncn.cashflow.Reminder}:java.lang.NullPointerException:尝试调用虚方法' void android.widget .ListView.setAdapter(android.widget.ListAdapter)'在null对象引用上               在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)               在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)               在android.app.ActivityThread.access $ 800(ActivityThread.java:151)               在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1303)               在android.os.Handler.dispatchMessage(Handler.java:102)               在android.os.Looper.loop(Looper.java:135)               在android.app.ActivityThread.main(ActivityThread.java:5257)               at java.lang.reflect.Method.invoke(Native Method)               在java.lang.reflect.Method.invoke(Method.java:372)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)        引起:java.lang.NullPointerException:尝试调用虚方法' void android.widget.ListView.setAdapter(android.widget.ListAdapter)'在null对象引用上               在com.gook.ever_ncn.cashflow.Reminder.displayData(Reminder.java:83)               在com.gook.ever_ncn.cashflow.Reminder.onCreate(Reminder.java:54)

我知道它只是一个空指针异常,但我再次检查我的代码很多次,我认为它不会有空指针异常错误。

请高手帮帮我,我必须做些什么?

先谢谢。

NB。到目前为止,这是我的代码Reminder.java(包含listview的活动):

public class Reminder extends ActionBarActivity {
Button btnReminder;
Button btnDateReminder;
EditText txtRemindAbout;
private ListView listRemind;
static final int DIALOG_ID=0;
private ArrayList<String> arrRemindId = new ArrayList<String>();
private ArrayList<String> arrRemindDateMentah = new ArrayList<String>();
private ArrayList<String> arrRemindDate = new ArrayList<String>();
private ArrayList<String> arrRemindAbout = new ArrayList<String>();
SQLiteDatabase db;
DatabaseHelper dBHelper = new DatabaseHelper(this);
private AlertDialog.Builder build;
public static String month, monthZ, dayZ ;
public static String dateSelected, dateSelectedShow;
int year_x, month_x, day_x;
private boolean isUpdateTrans;
String id, dateMentah, dateShow, about;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reminder);
    listRemind = (ListView) findViewById(android.R.id.list);
    btnDateReminder = (Button)findViewById(R.id.btnDateRemind);
    btnReminder = (Button) findViewById(R.id.btnAddTrans);
    displayData();
    onButtonClickButtonListener();
    onLongClickListener();
    selectDate();


}

private void displayData() {
    db = dBHelper.getReadableDatabase();
    Cursor mCursor = db.rawQuery("SELECT * FROM " + dBHelper.TABLE_Reminder_NAME + " WHERE DateMentah = "+dateSelected, null);

    arrRemindId.clear();
    arrRemindDateMentah.clear();
    arrRemindDate.clear();
    arrRemindAbout.clear();
    if (mCursor.moveToFirst()) {
        do {
            arrRemindId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.ROL1)));
            arrRemindDateMentah.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.ROL2)));
            arrRemindDate.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.ROL3)));
            arrRemindAbout.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.ROL4)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapterRemind disadptr = new DisplayAdapterRemind(Reminder.this, arrRemindId, arrRemindDateMentah, arrRemindDate,
            arrRemindAbout);
    //listRemind = (ListView) listRemind.findViewById(R.id.listRemind);
    listRemind = (ListView) findViewById(android.R.id.list);
    listRemind.setAdapter(disadptr);
    mCursor.close();

    listRemind.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            id = arrRemindId.get(arg2);
            dateSelected = arrRemindDateMentah.get(2);
            dateSelectedShow = arrRemindDate.get(2);
            txtRemindAbout.setText(arrRemindAbout.get(2));
            isUpdateTrans = true;

            // belum di coba, klo nda bisa yaudh dsni tampung pke string dlu baru lempar ke method lain nanti disana
            //yang dateSelectedShwo di set ke Btn nya
        }
    });
}

public void updateReminder(){
    Bundle bundle= getIntent().getExtras();
    if(bundle!= null) {
        isUpdateTrans = getIntent().getExtras().getBoolean("update");
        if (isUpdateTrans) {
            System.out.print("isUpdate di NewTrans");
            id = getIntent().getExtras().getString("remindId");
            dateMentah = getIntent().getExtras().getString("dateMentah");
            dateShow = getIntent().getExtras().getString("dateShow");
            about = getIntent().getExtras().getString("about");
            btnDateReminder.setText(dateShow);

        }
    }
}

public void onButtonClickButtonListener() {
    btnReminder.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        if (isUpdateTrans) {
                            //update
                            boolean isInserted = dBHelper.updateReminder(id, dateSelected, dateSelectedShow,
                                    txtRemindAbout.getText().toString(), null);
                            if (isInserted == true) {
                                clearText();
                                Toast.makeText(Reminder.this, "Updated", Toast.LENGTH_LONG).show();

                            } else
                                Toast.makeText(Reminder.this, "Not Inserted", Toast.LENGTH_LONG).show();
                        } else {
                            //insert
                            boolean isInserted = dBHelper.insertReminder(dateSelected, dateSelectedShow,
                                    txtRemindAbout.getText().toString(), null);
                            if (isInserted == true) {
                                clearText();
                                Toast.makeText(Reminder.this, "Inserted", Toast.LENGTH_LONG).show();
                            } else
                                Toast.makeText(Reminder.this, "Not Inserted", Toast.LENGTH_LONG).show();
                        }
                }
            });
}



private void selectDate(){
    final Calendar cal = Calendar.getInstance();
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    String date = df.format(cal.getTime());

    year_x = cal.get(Calendar.YEAR);
    month_x = cal.get(Calendar.MONTH);
    day_x = cal.get(Calendar.DAY_OF_MONTH);
    switchMonth(month_x + 1);
    monthZero(month_x + 1);
    dayZero(day_x);
    btnDateReminder = (Button)findViewById(R.id.btnDate);
    btnDateReminder.setText("Date : " + date);
    //btnIDate.setText("Date : " + day_x + "-" + month + "-" + year_x);
    dateSelected = (year_x+"-"+monthZ+"-"+dayZ);
    dateSelectedShow = dayZ + "-" +month+"-"+year_x;
}

@Override
protected Dialog onCreateDialog(int id){
    if (id == DIALOG_ID)
        return  new DatePickerDialog(this, dpickerListener , year_x, month_x, day_x);
    return null;

}


public DatePickerDialog.OnDateSetListener dpickerListener
        = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        year_x= year;
        month_x = monthOfYear + 1;
        day_x = dayOfMonth;
        switchMonth(month_x);
        monthZero(month_x);
        dayZero(day_x);
        Log.d("Month", "Anjret" + month_x);
        btnDateReminder.setText("Date : " + day_x + "-" + month + "-" + year_x);
        dateSelected = (year_x+"-"+monthZ+"-"+dayZ);
        dateSelectedShow = dayZ + "-" +month+"-"+year_x;
        displayData();

    }
};



private void onLongClickListener(){
    ListView list = (ListView)findViewById(android.R.id.list);
    list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
            build = new AlertDialog.Builder(Reminder.this);
            build.setTitle("Delete " + arrRemindAbout.get(arg2));
            build.setMessage("Do you want to delete ?");
            build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(getApplicationContext(),
                            arrRemindId.get(arg2) + " is deleted.", Toast.LENGTH_LONG).show();

                    db.delete(
                            dBHelper.TABLE_Trans_NAME, dBHelper.TOL1 + "=" + arrRemindId.get(arg2), null);
                    //String catSelected = mainAct.getCatSelected();
                    displayData();
                    dialog.cancel();
                }
            });

            build.setNegativeButton("No", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog alert = build.create();
            alert.show();

            return true;
        }
    });
}


private String switchMonth(Integer month_x){
    switch(month_x){
        case 1 : month = "Jan";
            break;
        case 2 : month = "Feb";
            break;
        case 3 : month = "Mar";
            break;
        case 4 : month = "Apr";
            break;
        case 5 : month = "Mei";
            break;
        case 6 : month = "Jun";
            break;
        case 7 : month = "Jul";
            break;
        case 8 : month = "Aug";
            break;
        case 9 : month = "Sep";
            break;
        case 10 : month = "Okt";
            break;
        case 11 : month = "Nov";
            break;
        case 12 : month = "Des";
            break;
    }
    return month;
}
private String monthZero(Integer month_x){//untuk nambahin 0 di depan bulan satu bilangan
    switch(month_x){
        case 1 : monthZ = "0"+month_x;
            break;
        case 2 : monthZ = "0"+month_x;
            break;
        case 3 : monthZ = "0"+month_x;
            break;
        case 4 : monthZ = "0"+month_x;
            break;
        case 5 : monthZ = "0"+month_x;
            break;
        case 6 : monthZ = "0"+month_x;
            break;
        case 7 : monthZ = "0"+month_x;
            break;
        case 8 : monthZ = "0"+month_x;
            break;
        case 9 : monthZ = "0"+month_x;
            break;
        case 10 : monthZ = String.valueOf(month_x);
            break;
        case 11 : monthZ = String.valueOf(month_x);
            break;
        case 12 : monthZ = String.valueOf(month_x);
            break;
    }
    return monthZ;
}
private String dayZero(Integer day_x){//untuk nambahin 0 di depan bulan satu bilangan
    if(day_x < 10){
        switch(day_x) {
            case 1:
                dayZ = "0" + day_x;
                break;
            case 2:
                dayZ = "0" + day_x;
                break;
            case 3:
                dayZ = "0" + day_x;
                break;
            case 4:
                dayZ = "0" + day_x;
                break;
            case 5:
                dayZ = "0" + day_x;
                break;
            case 6:
                dayZ = "0" + day_x;
                break;
            case 7:
                dayZ = "0" + day_x;
                break;
            case 8:
                dayZ = "0" + day_x;
                break;
            case 9:
                dayZ = "0" + day_x;
                break;
        }
    }else{
        dayZ = String.valueOf(month_x);
    }
    return dayZ;

}

private void clearText() {
    txtRemindAbout.setText("");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_reminder, menu);
    return true;
}

@Override
public void onBackPressed()
{
    super.onBackPressed();
    startActivity(new Intent(Reminder.this, MainActivity.class));
    finish();

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if(id == android.R.id.home){
        finish();
    }

    switch (id) {
        case R.id.action_settings:
            Intent intentCategSetting = new Intent(Reminder.this, CategorySetting.class);
            startActivity(intentCategSetting);
            finish();
            break;
        case R.id.menu_rate:
            Toast.makeText(Reminder.this, "Rate Broo", Toast.LENGTH_LONG);
            break;
        case R.id.menu_about:
            Intent intentAbout = new Intent(Reminder.this, AboutUs.class);
            startActivity(intentAbout);
            finish();
            break;
    } return super.onOptionsItemSelected(item);
}

}

activity_reminder.xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gook.ever_ncn.cashflow.Reminder">

<include
    android:id="@+id/app_bar"
    layout="@layout/app_bar"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Reminder List"
    android:id="@+id/textView14"
    android:layout_below="@+id/app_bar"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Reminder"
    android:id="@+id/textView18"
    android:layout_marginBottom="60dp"
    android:layout_above="@+id/editText3"
    android:layout_alignRight="@+id/btnRemindMe"
    android:layout_alignEnd="@+id/btnRemindMe" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText3"
    android:hint="Reminder About"
    android:layout_above="@+id/btnRemindMe"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Remind Me"
    android:id="@+id/btnRemindMe"
    android:layout_marginBottom="53dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/custom_button"/>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Date"
    android:id="@+id/btnDateRemind"
    android:layout_above="@+id/editText3"
    android:layout_centerHorizontal="true"
    android:background="@drawable/custom_button"/>

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listRemind"
    android:layout_below="@+id/textView14"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/textView18" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Reminder"
    android:id="@+id/textView19"
    android:textColor="#f325272f"
    android:textStyle="bold"
    android:layout_below="@+id/app_bar"
    android:layout_centerHorizontal="true" />

2 个答案:

答案 0 :(得分:1)

你在这里做错了

 listRemind = (ListView) findViewById(android.R.id.list);

应该是

 listRemind = (ListView) findViewById(R.id.listRemind);

答案 1 :(得分:0)

在你的活动的onCreate()中

 ListView  listRemind = findViewById(R.id.listRemind);

这是你在运行时得到空引用的原因......