使用SQLite时出现Nullpointer异常

时间:2015-09-12 04:56:39

标签: android sqlite

我正在使用sqlitedatabase,我能够正确插入数据,但问题是当我试图显示插入的数据时,我的应用程序崩溃并给出nullpointer异常,任何人都可以告诉我的代码有什么问题,以下是我的代码段,

此行中的错误

 if (c1 != null & c1.getCount() != 0) {

MAinActivity.java

public class MainActivity extends Activity {

    private ListView upcominglist;


    private ListView todays;
    private ListView eventhistory;
    private ImageView addnewevent;

    public ArrayList<ContactListItems> contactList;

    public ContactListItems contactListItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        upcominglist=(ListView)findViewById(R.id.listview_upcoming);
        todays=(ListView)findViewById(R.id.listview_todays);
        eventhistory=(ListView)findViewById(R.id.listview_eventhistory);

        addnewevent=(ImageView)findViewById(R.id.addneweventbutton);

        addnewevent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
                startActivity(intent);
            }
        });


       contactList = new ArrayList<ContactListItems>();
        contactList.clear();
        String query = "SELECT * FROM PHONE_CONTACTS ";
        Cursor c1 = SqlHandler.selectQuery(query);
        if (c1 != null & c1.getCount() != 0) {
            if (c1.moveToNext()) {
                do {
                    contactListItems = new ContactListItems();
                    contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
                    contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
                    contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
                    contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
                    contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
                    contactList.add(contactListItems);
                } while (c1.moveToNext());
            }
        }
        else
        {
            c1.close();
        }
       c1.close();

        String first=contactListItems.getSlno();
        System.out.println("First" + first);

        String second=contactListItems.getNameofevent();
        System.out.println("SEcond"+second);

        String third=contactListItems.getDtofevent();
        System.out.println("Third"+third);

        String fourth=contactListItems.getTimeofevent();
        System.out.println("Fourth"+fourth);

        String fifth=contactListItems.getDuration();
        System.out.println("Fifth"+fifth);
    }

Addnewevent.java

public class AddNewEvent extends Activity {

    private int year;
    private int month;
    private int day;
    static final int DATE_PICKER_ID = 1111;

    static final int TIME_PICKER_ID = 11111;

    int flag = 0;

    private ImageView addnewdata;
    private LinearLayout lnr;
    private Button submit;
    private EditText edtnmofevent;
    private EditText edtdtofevent;
    private EditText edttmofevent;
    private EditText edtdurationofevent;
    SqlHandler sqlHandler;

    private ImageView datepicks;
    private ImageView timepicks;


    private Calendar cal;
    private int hour;
    private int min;


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

        sqlHandler = new SqlHandler(getApplicationContext());


        addnewdata = (ImageView) findViewById(R.id.addnewdata);
        submit = (Button) findViewById(R.id.btnsubmit);
        edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
        edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
        edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
        edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);

        datepicks = (ImageView) findViewById(R.id.calndrdat);

        timepicks = (ImageView) findViewById(R.id.timepickrs);
        cal = Calendar.getInstance();
        hour = cal.get(Calendar.HOUR_OF_DAY);
        min = cal.get(Calendar.MINUTE);

        timepicks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(TIME_PICKER_ID);
            }
        });

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
                .append(year).append(" ");

        // for Converting Correct Date format Save into Database
        SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
        String abs1 = dateValue1.toString();
        Date testDate1 = null;
        try {
            try {
                testDate1 = sdf123.parse(abs1);
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }
        SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
        String DateFormat = formatter1.format(testDate1);

        edtdtofevent.setText(DateFormat);

        edtdtofevent.setFocusable(false);
        edtdtofevent.setInputType(InputType.TYPE_NULL);
        datepicks.setOnClickListener(new View.OnClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                showDialog(DATE_PICKER_ID);
            }
        });

        addnewdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
                View promptsView = li.inflate(R.layout.prompts, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        AddNewEvent.this);
                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);
                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);

                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                        lnr = (LinearLayout) findViewById(R.id.addnewlinear);
                                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                                LinearLayout.LayoutParams.WRAP_CONTENT);
                                        lp.setMargins(25, 0, 0, 0);
                                        TextView valueTV = new TextView(AddNewEvent.this);
                                        // valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                        valueTV.setText(userInput.getText());
                                        valueTV.setLayoutParams(lp);
                                        valueTV.setTextSize(18);
                                        valueTV.setTextColor(Color.parseColor("#2d6cae"));
                                        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                                LinearLayout.LayoutParams.WRAP_CONTENT);
                                        lp1.setMargins(25, 0, 25, 0);
                                        lp1.height = 50;
                                        EditText edtvalues = new EditText(AddNewEvent.this);
                                        edtvalues.setBackgroundResource(R.drawable.rect_edt);
                                        edtvalues.setLayoutParams(lp1);
                                        lnr.addView(valueTV);
                                        lnr.addView(edtvalues);
                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                AlertDialog alertDialog = alertDialogBuilder.create();

                alertDialog.show();

            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
                startActivity(intent);
                String nameofevent = edtnmofevent.getText().toString();
                String dtofevent = edtdtofevent.getText().toString();
                String timeofevent = edttmofevent.getText().toString();
                String duration = edtdurationofevent.getText().toString();
                String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
                        + nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
                sqlHandler.executeQuery(query);
                System.out.println("Querys" + query);
            }
        });
    }

SQL

public class SqlDbHelper extends SQLiteOpenHelper {
    public static final String DATABASE_TABLE = "PHONE_CONTACTS";

    public static final String COLUMN1 = "slno";
    public static final String COLUMN2 = "nameofevent";
    public static final String COLUMN3 = "dtofevent";
    public static final String COLUMN4 = "timeofevent";
    public static final String COLUMN5 = "duration";
   /* public static final String COLUMN6 = "dlabl";
    public static final String COLUMN7 = "dedt";*/

    private static final String SCRIPT_CREATE_DATABASE = "create table "
            + DATABASE_TABLE + " (" + COLUMN1
            + " integer primary key autoincrement, " + COLUMN2
            + " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";

    public SqlDbHelper(Context context, String name, CursorFactory factory,
                       int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(SCRIPT_CREATE_DATABASE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }

}

2 个答案:

答案 0 :(得分:2)

问题在于您的SqlHandler.selectQuery()返回null,另一个问题是检查结果:

if (c1 != null & c1.getCount() != 0)

您正在使用按位和&而不是短路逻辑和&&。在没有短路的情况下,评估c1.getCount()引用上包括null的完整表达式。

答案 1 :(得分:1)

这里有太多解释,所以我会给你一些导致空指针异常的缺陷。 我可以看到你的编程方法来自过于担心关闭事物和清理 资源到一定程度,它会造成问题。

contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
    // Move to the first entry.
    c1.moveToFirst();
    //if (c1.moveToNext()) {
    //    do {
    // Continue while it has not passed the last entry.
    while (!cursor.isAfterLast())
            contactListItems = new ContactListItems();
            contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
            contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
            contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
            contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
            contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
            contactList.add(contactListItems);
            // Move the cursor along to the next entry.
            cursor.moveToNext();
        } 
    }
    // Close cursor after while and within if (so you know it is not null).
    c1.close();
}
else
{
    // You can't close c1 if it is Null. This will throw and error. Lose the else.
    c1.close();
}
// Move this to within your if statment.
c1.close();

来自您在聊天中提供的代码。 不要连续打开和关闭数据库,只需关闭完成后使用的每个光标。只需在程序运行的开始和结束时打开它。

public static Cursor selectQuery(String query) {
    Cursor c1 = null;
    try {

        if (sqlDatabase.isOpen()) {

            // You are closing the database.
            sqlDatabase.close();

        }
        sqlDatabase = dbHelper.getWritableDatabase();
        c1 = sqlDatabase.rawQuery(query, null);

    } catch (Exception e) {

        System.out.println("DATABASE ERROR " + e);

    }
    return c1;
}

您的项目还有许多其他缺陷。就像结构以及如何以及何时召唤事物一样。您需要将其模块化,为特定任务创建方法并调用这些方法,而不是在oncreate中使用大量代码。
我相信你会对此有很多疑问。但是目前这个问题正在解决你的空指针异常,这就是我将在这里讨论的内容。有关与此例外无关的问题,请提出新问题。希望这会有所帮助。