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;
}
Related
I have 2 classes which connect to a database. But with my current implementation I have to connect to 2 different databases.How can I fix this? If I use the same name for both databases it gives me an error
One class.....
public static final String DATABASE_NAME = "140398L.db";
Context context;
public PersistantAccountDAO(Context context) {
super(context, DATABASE_NAME, null, 1);
this.context = context;
}
Other class......
public class PersistantTransactionDAO extends SQLiteOpenHelper implements TransactionDAO {
public static final String DATABASE_NAME = "140398L";
public PersistantTransactionDAO(Context context) {
super(context, DATABASE_NAME, null, 1);
}
The DatabaseName is different, one class is 140398L.db and the other is 140398L
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.
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}
With the below code, nothing appears in the ListActivity as I would expect.
No errors are shown in logcat.
Arrival.java
package one.two;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Arrival extends ListActivity
{
private ListView listView;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
ArrayList<String> retList = new ArrayList<String>();
System.out.println("Start onCreate Function\n");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("In onCreate Function\n");
System.out.println("In of GetData\n");
DBAdapter db = new DBAdapter(this);
System.out.println("DB Open\n");
db.open();
System.out.println("DB Opened\n");
retList = getData();
System.out.println("Out of GetData\n");
// force count no. of records in table
// dump to check index
int cnt = 2;
int i=0;
for (i = 0; i<cnt; i++)
System.out.println(retList.toString());
System.out.println("Array 2 String\n");
Cursor c = db.getCursor();
String[] from = new String[] {DBAdapter.status};
int[] to = new int[] {R.id.txt1};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.listtext, c, from, to);
this.setListAdapter(mAdapter);
System.out.println("Show List\n");
db.close();
}
public static ArrayList<String> getData()
{
ArrayList<String> items = DBAdapter.getAllTitles();
System.out.println("Return a LIST titles\n");
return items;
}
}
DBAdapter.java
package one.two;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.util.ArrayList;
public class DBAdapter
{
public static String status = "status";
public String id = "id";
public String arrival = "arrival";
public String destination = "destination";
public String ferry = "ferry";
private static String DB_PATH = "/data/data/one.two/databases/";
private static final String DATABASE_NAME = "ferry.db";
private static final String DATABASE_TABLE = "port";
public static Context context;
public Cursor c;
public static SQLiteDatabase DbLib;
//overloaded non-null constructor
public DBAdapter(Context context)
{
DbLib = context.openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY,null);
System.out.println("OpenOrCreateDB Done");
}
public class DatabaseHelper extends SQLiteOpenHelper
{
Context context;
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}//end constructor DatabaseHelper
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}//end onUpgrade()
#Override
public void onCreate(SQLiteDatabase db)
{
}//end onCreate()
}// end class DatabaseHelper
private static DatabaseHelper DBHelper;
//private static SQLiteDatabase DbLib;
private static final int DATABASE_VERSION = 1;
public static ArrayList<String> getAllTitles()
{
ArrayList<String> port = new ArrayList<String>();
Cursor c=null;
c = DbLib.query("port",
new String[] { "status", "id", "arrival",
"destination", "ferry" }, null, null,
null, null, null);
try {
if (c!=null) { // start - when there is at least 1 record
System.out.println("Cursor is NOT NULL");
int i =0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
// Debug Stm
System.out.println("Record No. "+i);
System.out.println(c.getString(0));
System.out.println(c.getString(1));
System.out.println(c.getString(2));
System.out.println(c.getString(3));
System.out.println(c.getString(4));
// Assign database cursor.records to arraylist
port.add(i,c.getString(0));
port.add(i,c.getString(1));
port.add(i,c.getString(2));
port.add(i,c.getString(3));
port.add(i,c.getString(4));
i = i + 1;
}
} // end - where there is at least 1 record
} finally {
if (c!=null) {
c.close();
}
}
return port;
}//end getAllTitles()
public void open() {
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
DbLib = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public Cursor getCursor(){
return c;
}
public void close()
{
DbLib.close();
}
}//end class DBAdapter
main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- snip... -->
<ListView
android:layout_width="wrap_content"
android:layout_y="132dip"
android:layout_x="150dip"
android:id="#android:id/list"
android:layout_height="wrap_content">
</ListView>
At a quick guess, I'd say it's because you're closing the database connection in your onCreate method, before the list adapter has a chance to read any data from it. The Cursor itself doesn't contain all the data as soon as you run a query.
If you want your Activity to handle closing the database connection, you should do so in the onPause or onDestroy method.