Could you please help me with error "java.lang.NullPointerException". I use custom listpreference to show elements from database. There two files CustomListPreference.java and DbHelper.java
CustomListPreference.java
public class CustomListPreference extends ListPreference {
CustomListPreferenceAdapter customListPreferenceAdapter = null;
Context mContext;
private SQLiteDatabase db;
DbHelper dbHelp = new DbHelper(mContext);
public CustomListPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
mInflater = LayoutInflater.from(context);
}
#Override
protected void onPrepareDialogBuilder(Builder builder)
{
...
try {
db = dbHelp.getReadableDatabase();//I get error java.lang.NullPointerException
...
}
DbHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="myBase";
public static final String KEY_NAME="name";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tUser ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "exists integer" + ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
because your mContext is null
place this line inside constructor..or any of your other preferece methods before using it
dbHelp = new DbHelper(context);
Context mContext;
private SQLiteDatabase db;
DbHelper dbHelp = new DbHelper(mContext);
The mContext you passed to DbHelper constructor is null.
You should not initialize any class member requiring a valid Context until onCreate() anyway.
Related
I have database and i want fill it with some values from xml file.
I'm using this code stream = context.getResources().openRawResource(R.xml.test_entry); to define the stream, but context make error "cannot resolve symbol 'context'".
I tried replace context with getActivity(), getContext(), this, class name and it still doesn't work. I need some help...
public class DatabaseHelper extends SQLiteOpenHelper {
<...>
public DatabaseHelper(Context context) {
super(context, dbName, null, dbv);
}
public void onCreate (SQLiteDatabase db) {
<...>
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+tableName);
onCreate(db);
/////////////////
loadTestValuyes(); <----- My function
/////////////////
}
public void loadTestValuyes() {
test_addEntry stackOverflowXmlParser = new test_addEntry();
List<Entry> entries = null;
InputStream stream = null;
///// I need context here
stream = context.getResources().openRawResource(R.xml.test_entry);
/////////////////
try {
entries = stackOverflowXmlParser.parse(stream);
} finally {
if (stream != null) {
stream.close();
}
}
for (Entry entry : entries) {
<...>
}
}
}
Thanks
You're passing a Context as a constructor argument. Just store it to a member variable:
private Context mContext;
public DatabaseHelper(Context context) {
super(context, dbName, null, dbv);
mContext = context;
and then use mContext where you need a Context.
You can save a reference to the Context object as an instance variable and use it wherever you need it:
public class DatabaseHelper extends SQLiteOpenHelper {
private Context mContext;
public DatabaseHelper(Context context) {
super(context, dbName, null, dbv);
mContext = context;
}
}
hello i am building a SQLite Db for my android application . this is the code :
package com.example.pap_e;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class FeedsDbAdapter {
private final Context mCtx;
private static final String DEBUG_TAG = "RSSDatabase";
private static final int DB_VERSION = 1;
private static final String DB_NAME = "rss_data";
public static String TABLE = "list";
public static final String ID = "_id";
public static final String RSS = "_rss";
public static final String TITLE = "_title";
public static final String PUBDATE = "_pubdate";
public static final String DESCRIPTION = "_description";
public static final String LINK = "_link";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE_TABLE"+TABLE+"("+ID+ "integer PRIMARY KEY AUTOINCREMENT,"+RSS+"text NOT NULL,"
+TITLE+"text NOT NULL,"+PUBDATE+"text NOT NULL,"+DESCRIPTION+"text NOT NULL,"+LINK+"text NOT NULL"+")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);}
}
public FeedsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean updateAnakoinosi(long rowId, String rss, String title,
String pubdate, String description, String link) {
ContentValues args = new ContentValues();
args.put(RSS, rss);
args.put(TITLE, title);
args.put(PUBDATE, pubdate);
args.put(DESCRIPTION, description);
args.put(LINK, link);
return mDb.update(TABLE, args, ID + "=" + rowId, null) > 0;}
public Cursor fetchAllAnakoinoseis() {
return mDb.query(TABLE, new String[] { ID, RSS, TITLE, PUBDATE,
DESCRIPTION,LINK }, null, null, null, null, null); }
}
The thing is that i get an error at public class FeedsDbAdapter that says:"The blank final field mCtx may not have been initialized" but i had it initialized using private final Context mCtx; Am i missing something here ? Thanks a lot in advance!
You didn't initialize the context yet. You have to initialize it inside FeedsDbAdapter constructor like :
public FeedsDbAdapter (Context context){
mCtx = context;
}
first declare FeedsDbAdapter constructor, because you use FeedsDbAdapter class through its constructor in other classes ans the other activity context will assign to this current context.
Change your code to :
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mCtx = context;
}
This question of yours relates to java. This line private final Context mCtx; is just a declaration of field mCtx of type context. And as this field has been declared as final, It has to be iniliazed inside the constructor mCtx = context;. Even if mCtx is not declared as final, it has still to be initialized before being used.
Thats because your class is static... Remove static from your class and change your code to
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mCtx = context;
}
I have created DBAdapter class which is responsible for making a connection to a Database and does any query and finally close the connection.
I have another class which it is not inherited from Activity class(ReminderBeep), but i have to use my DBAdapter in this class.
Actually i don't know how can i manipulate the DBAdapter constructor to make the connection.*
The error is: The constructor DBAdapter(ReminderBeep) is undefined
DBAdapter is:
public class DBAdapter {
static final String DATABASE_NAME = "MyDB";
static final int DATABASE_VERSION = 2;
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void insert(String sql)
{
db.execSQL(sql);
}
}
BeepReminder is:
public class ReminderBeep
{
public void DeleteDailyActivities()
{
DBAdapter db=new DBAdapter(this);
db.open();
String sql="delete from DailyWorks";
db.insert(sql);
db.close();
}
}
ReminderBeep is not extendig Activity. But DBAdapter want a Context as paramter,
DBAdapter db=new DBAdapter(this);
this refers to ReminderBeep
been pulling my hair out with an app I am trying to build. I have tried so many different things, books, ways, youtube tutorials I have lost count! I am building a simple app which shows pictures of aircraft then the user clicks to add it to a learnt list (verified that is working by using toast instead of listview) then clicks another button to view this list.
I have the app returning the correct number of rows but they are all blank! From what I have read this means the rows are null but I can't for the life of me figure what is wrong! I would be forever in the debt of whoever can help :)
Thanks! Here's the code...
(database helper/adapter)
package com.atcapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
private static final String TAG = "DatabaseAdapter";
private static final String DATABASE_NAME = "LearntListdb";
private static final String DATABASE_TABLE = "AircraftTable";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table AircraftTable (_id integer primary key autoincrement, "
+ "name text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DatabaseAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + "which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS AircraftNames");
onCreate(db);
}
}
// ---opens the database---
public DatabaseAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
// ---insert an aircraft into the database---
public long insertAircraft(String name) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
return db.insert(DATABASE_TABLE, null, initialValues);
}
// ---retrieves all the list---
public Cursor getAllAircraft() {
Cursor c = db.query(DATABASE_TABLE, new String[] {"_id", "name"}, null, null, null, null, null);
return c;
}
}
(List Activity)
package com.atcapp;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class DataView extends ListActivity {
private DatabaseAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aircraftlist);
mDbHelper = new DatabaseAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData(){
Cursor c = mDbHelper.getAllAircraft();
startManagingCursor(c);
String[] from = new String[] {DatabaseAdapter.KEY_ROWID, DatabaseAdapter.KEY_NAME};
int[] to = new int[] {android.R.id.list};
SimpleCursorAdapter myList =
new SimpleCursorAdapter(this, R.layout.list_row, c, from, to);
setListAdapter(myList);
}
}
You need to supply textview ids in your to array. You need to be mapping data from the cursor to views in the adapter.
Look in your list_row layout and use the textview id from there.
Hey guys I already have a data in my database but I want to show it into spinner I'm really new to this problem, so would you guys help me to solve this problem,or I would prefer if you write the correct code for me :) Thanks in advance.
First this is my DB class
public class DBAdapter
{
public static final String UPDATEDATE = "UpdateDate";
//Declare fields in PersonInfo
public static final String ROWID = "_id";
public static final String PT_FNAME = "Username";
public static final String PT_COLORDEF = "ColorDeficiency";
private static final String DATABASE_CREATE =
"create table PersonInfo (_id integer primary key autoincrement, "
+ "Username text not null, ColorDeficiency text);";
private static final String DATABASE_NAME = "CAS_DB";
private static final String tbPerson = "PersonInfo";
private static final int DATABASE_VERSION = 1;
private final Context databaseContext;
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
databaseContext = ctx;
}
//start database helper
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor all(Activity activity){
String[] from ={ROWID,PT_FNAME,PT_COLORDEF};
String order = PT_FNAME;
Cursor cursor =db.query(tbPerson, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
In another class
private DBAdapter db;
private Spinner spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greeting);
initComponent();
db = new DBAdapter(this);
Cursor c = db.all(this);
SimpleCursorAdapter CursorAdapter = new SimpleCursorAdapter(
this,android.R.layout.simple_spinner_item,c,
new String[]{DBAdapter.PT_FNAME},new int[]{android.R.id.list});
CursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(CursorAdapter);
try changing
new int[]{android.R.id.list}
to
new int[]{android.R.layout.simple_spinner_item}