i’ve problem access other class in android…
i’ve class databasex (non static) and class CountingFragment (static)….
in CountingFragment i want to access databasex class..but i get result null….
here is my piece of code…
class Databasex
public class DataBasex {
public static final String KEY_ROWID="_id";
public static final String KEY_NAME="namaLokasi";
public static final String KEY_JENIS="jenis";
public static final String KEY_KETERANGAN="ket";
public static final String tanda="DataBasex";
private static final String DATABASE_NAME="DbPeta";
private static final String DATABASE_TABLE="lokasi";
private static final int DATABASE_VERSION=1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(tanda,"dbHelper-> "+context);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.i(tanda,"onCreate-> "+db);
/*db.execSQL("CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME +" TEXT NOT NULL, " + KEY_JENIS +" TEXT NOT NULL, " +
KEY_KETERANGAN +" TEXT NOT NULL);");
*/
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.i(tanda,"onUpgrade-> "+db);
//db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
//onCreate(db);
}
}
public DataBasex(Context c){
ourContext =c;
Log.i(tanda,"DataBasex-> "+ourContext);
}
public DataBasex open() throws SQLException{
Log.i(tanda,"DataBasex open awal ");
ourHelper = new DbHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
Log.i(tanda,"DataBasex open-> "+ourDatabase);
return this;
}
public void close(){
Log.i(tanda,"[close]");
ourHelper.close();
}
}
and here is CountingFragment class…
public static class CountingFragment extends SherlockFragment {
//here myproblem...
DataBasex con=new DataBasex(getSherlockActivity());
/**
*other method
*/
}
i think the code bellow is my problem
DataBase con=new DataBase(getSherlockActivity());
if in non-static class i use code bellow and everything is ok….but in static class i can’t…why??
DataBase con=new DataBase(this);
It is due to the fact that
Fragments need to first be attached to an Activity (see the document onFragments before they can return an Activity. Specifically the lifecycle. First the Fragment is attached to an Activity (andonAttach()is called. Then the Fragment can get an Activity instance.is in the root of the Class, it will return null – the Fragment does not have an Activity right off the bat.
Change
So it is:
And add this method: