traducir pointer java android database nullpointerexception android-sqlite

java - null pointer exception traducir



NullPointerException en getReadableDatabase() (4)

Tengo este método en una clase (no actividad) -

public boolean usernameChk(String usrname) { String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = ''" + usrname + "''"; SQLiteDatabase db = this.getReadableDatabase(); //NullPointerException on line above Cursor cursor = db.rawQuery(usrnmQuery, null); cursor.close(); if (cursor.getCount() <= 0) { return false; } else { return true; } }

Pero obtengo NullPointerException en línea SQLiteDatabase db = this.getReadableDatabase(); cuando llamo a este método de otra actividad -

private Context context; this.context = context; new DatabaseHandler(this); DatabaseHandler dbz = new DatabaseHandler(context); boolean z = dbz.usernameChk(username.getText().toString());

Aquí está mi LogCat -

09-02 10:28:11.906: W/ApplicationPackageManager(9380): getCSCPackageItemText() 09-02 10:28:12.171: D/OpenGLRenderer(9380): Enabling debug mode 0 09-02 10:28:13.881: W/ApplicationPackageManager(9380): getCSCPackageItemText() 09-02 10:28:18.436: D/AndroidRuntime(9380): Shutting down VM 09-02 10:28:18.436: W/dalvikvm(9380): threadid=1: thread exiting with uncaught exception (group=0x4180ec08) 09-02 10:28:18.441: E/AndroidRuntime(9380): FATAL EXCEPTION: main 09-02 10:28:18.441: E/AndroidRuntime(9380): Process: com.Atlantiz.diary, PID: 9380 09-02 10:28:18.441: E/AndroidRuntime(9380): java.lang.NullPointerException 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188) 09-02 10:28:18.441: E/AndroidRuntime(9380): at com.Atlantiz.diary.DatabaseHandler.usernameChk(DatabaseHandler.java:142) 09-02 10:28:18.441: E/AndroidRuntime(9380): at com.Atlantiz.diary.Create.onClick(Create.java:42) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.view.View.performClick(View.java:4633) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.view.View$PerformClick.run(View.java:19330) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.os.Handler.handleCallback(Handler.java:733) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.os.Handler.dispatchMessage(Handler.java:95) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.os.Looper.loop(Looper.java:157) 09-02 10:28:18.441: E/AndroidRuntime(9380): at android.app.ActivityThread.main(ActivityThread.java:5356) 09-02 10:28:18.441: E/AndroidRuntime(9380): at java.lang.reflect.Method.invokeNative(Native Method) 09-02 10:28:18.441: E/AndroidRuntime(9380): at java.lang.reflect.Method.invoke(Method.java:515) 09-02 10:28:18.441: E/AndroidRuntime(9380): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) 09-02 10:28:18.441: E/AndroidRuntime(9380): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 09-02 10:28:18.441: E/AndroidRuntime(9380): at dalvik.system.NativeStart.main(Native Method)

Sé que este tipo de pregunta se hizo antes pero las soluciones dadas no funcionaron. ¿Alguna idea de cómo arreglarlo?

EDITAR

Constructor -

public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); }

Y clase -

package com.Atlantiz.diary; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "accountManager"; // Contacts table name private static final String TABLE_ACCOUNTS = "accounts"; // Contacts Table Columns names private static final String KEY_ID = "id"; private static final String KEY_F_NAME = "first_name"; private static final String KEY_L_NAME = "last_name"; private static final String KEY_USERNAME = "username"; private static final String KEY_EMAIL = "email"; private static final String KEY_PASSWORD = "password"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_F_NAME + " TEXT," + KEY_L_NAME + " TEXT," + KEY_USERNAME + " TEXT," + KEY_EMAIL + " TEXT," + KEY_PASSWORD + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNTS); onCreate(db); } // Adding new contact public void addContact(Accounts account) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_F_NAME, account.getFirst_name()); values.put(KEY_L_NAME, account.getLast_name()); values.put(KEY_USERNAME, account.getUsername()); values.put(KEY_EMAIL, account.getEmail()); values.put(KEY_PASSWORD, account.getPassword()); db.insert(TABLE_ACCOUNTS, null, values); db.close(); } // Getting single contact public Accounts getContact(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_ACCOUNTS, new String[] { KEY_ID, KEY_F_NAME, KEY_L_NAME, KEY_USERNAME, KEY_EMAIL, KEY_PASSWORD }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) cursor.moveToFirst(); Accounts account = new Accounts(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)); // return contact return account; } // Getting All Contacts public List<Accounts> getAllAccounts() { List<Accounts> AccountList = new ArrayList<Accounts>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_ACCOUNTS; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Accounts account = new Accounts(); account.setID(Integer.parseInt(cursor.getString(0))); account.setFirst_name(cursor.getString(1)); account.setLast_name(cursor.getString(2)); account.setUsername(cursor.getString(3)); account.setEmail(cursor.getString(4)); account.setPassword(cursor.getString(5)); // Adding contact to list AccountList.add(account); } while (cursor.moveToNext()); } // return contact list return AccountList; } // Getting contacts Count public int getContactsCount() { String countQuery = "SELECT * FROM " + TABLE_ACCOUNTS; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); cursor.close(); // return count return cursor.getCount(); } public boolean usernameChk(String usrname, Context context){ String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = ''" + usrname + "''"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(usrnmQuery, null); cursor.close(); if(cursor.getCount() <= 0){ return false; }else{ return true; } } // Updating single contact public int updateContact(Accounts account) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_F_NAME, account.getFirst_name()); values.put(KEY_L_NAME, account.getLast_name()); values.put(KEY_USERNAME, account.getLast_name()); values.put(KEY_EMAIL, account.getLast_name()); values.put(KEY_PASSWORD, account.getLast_name()); // updating row return db.update(TABLE_ACCOUNTS, values, KEY_ID + " = ?", new String[] { String.valueOf(account.getID()) }); } // Deleting single contact public void deleteContact(Accounts account) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_ACCOUNTS, KEY_ID + " = ?", new String[] { String.valueOf(account.getID()) }); db.close(); } }


Como su clase que no es una Activity this.getReadableDatabase(); está disparando NullPointerException ya que no está recibiendo contexto para abrir la base de datos.

Usa el contexto para abrir la base de datos. prueba con los siguientes:

DatabaseHandler dbz = new DatabaseHandler(Activity.this); public Context context; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // assigning context Change your constructor this.context = context; } // Open database using context object SQLiteDatabase db = this.getReadableDatabase();


De acuerdo con su código, el contexto no está definido.

usa esto en lugar de contexto cuando creas una nueva instancia de tu ayudante

DatabaseHandler dbz = new DatabaseHandler(this); boolean z = dbz.usernameChk(username.getText().toString());


El Context que pasas a tu constructor de DatabaseHandler es null .

Esa es la explicación para el NPE en getDatabaseLocked() . Para obtener ayuda para solucionarlo, publique el código donde inicializa el contexto.


No has pasado el contexto adecuado de tu actividad y es por eso que arroja un error nullpointer.

Simplemente cambie su método de la siguiente manera.

public boolean usernameChk(String usrname){ String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = ''" + usrname + "''"; SQLiteDatabase db = this.getReadableDatabase();

Declare un Context común en su DatabaseHelper y asigne el valor de constructor mientras crea la instancia de su clase auxiliar de la siguiente manera:

public Context m_context; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); m_context = context; }