-6

i have an android app with an main.class and a main_fragment.class

in the fragment class i have this code part:

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String query = "INSERT INTO " + SqlDbHelper.DATABASE_TABLE + " "
            + "(firstname,second name,bday) "
            + "values ('Max','Mustermann','20.05.2016')";

    Log.e ("-->",""+query);

    sqlHandler.executeQuery(query);
}

i would like set this values in my database table. but my app crash on this line with a java.lang.NullPointerException:

sqlHandler.executeQuery(query);

i don't understand this. my Log.e result:

INSERT INTO PRODUCTS (firstname,secondname,bday) values ('Max,'Mustermann','20.05.2016')

can anyone helps me?

UPDATE This is my sqlHandler.class

public class SqlHandler {

public static final String DATABASE_NAME = "DATABASE";
public static final int DATABASE_VERSION = 1;
Context context;
SQLiteDatabase sqlDatabase;
SqlDbHelper dbHelper;

public SqlHandler(Context context) {
    dbHelper = new SqlDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    sqlDatabase = dbHelper.getWritableDatabase();
}

public void executeQuery(String query) {
    try {

        if (sqlDatabase.isOpen()) {
            sqlDatabase.close();
        }

        sqlDatabase = dbHelper.getWritableDatabase();
        sqlDatabase.execSQL(query);

    } catch (Exception e) {

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

}

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

        if (sqlDatabase.isOpen()) {
            sqlDatabase.close();

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

    } catch (Exception e) {

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

    }
    return c1;

}

}

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
Trombone0904
  • 4,132
  • 8
  • 51
  • 104

1 Answers1

0

The first code snippet you have provided is not sufficient to answer the question with any degree of certainty. From the exception it would appear that the sqlHandler variable is null, but you have not provided any code to show how you are instantiating this.

sqlHandler seems to be a global variable, so you'll want to set it to an instance of the SqlHandler class before you use it, eg in the constructor of the class that uses it or just before calling one of its methods.

sqlHandler = new SqlHandler(*some var of type Context*);
ewanc
  • 1,284
  • 1
  • 12
  • 23