0

I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,

Error in this line

 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);
    }

}
1
  • thats the reason of nullpointer? Commented Sep 12, 2015 at 5:09

2 Answers 2

2

The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:

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

You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.

Sign up to request clarification or add additional context in comments.

3 Comments

as you can see select query is used in main activity..and insert is in addnewevent class
i put && now error is here.. else { c1.close(); }
i dont clear one thing that..when i run the app mainactivity will run...and without having data in table how select query works
1

There is too much here to explain it all, so I will give you the flaws causing a null pointer exception. I can see your method of programming is coming from worrying too much about closing things and clearing up resources to a point, it's causing problems.

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();

From your code you provided in the chat. Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.

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;
}

There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.