Cannot resolve context method - java

I'm trying to use database in my app and have created an helper class with onCreate and onUpgrade method and an constructor. Then in another class I try to create an object of my helper class with getContext() as they do on the android development documentation. But I get an error saying "cannot resolve method getContext()". I have googled and try like getApplicationContext and that doesn't work. This in the argument doesn't work either. Here is the class I try to write it:
public class SearchResultItem {
DbHelper dbHelper = new DbHelper(getContext());
#JsonKey("Title") // You need to write this so the jsonparser knows which value to get
private String mTitle;
#JsonKey("Year")
private String mYear;
#JsonKey("imdbID")
private String mImdbId;
#JsonKey("Type")
private String mType;
public String getTitle()
{
return mTitle;
}
public String getYear()
{
return mYear;
}
public String getImdbId()
{
return mImdbId;
}
public String getType()
{
return mType;
}
}
And my DbHelper class looks like this if it's needed:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "movies.db";
//Table name
private static final String MOVIE_TABLE = "movies";
//Column names
private static final String COLUMN_ID = "id";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_YEAR = "year";
private static final String COLUMN_PLOT = "plot";
Context context;
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { // Called when the database is created for the first time
final String SQL_MOVIE_TABLE = "CREATE TABLE IF NOT EXISTS " + MOVIE_TABLE + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_TITLE + " TEXT NOT NULL," +
COLUMN_YEAR + " REAL," + COLUMN_PLOT + " TEXT" + ")";
sqLiteDatabase.execSQL(SQL_MOVIE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { // Called when the database needs to be upgraded/changed or dropped
//Drop older table if it exists
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MOVIE_TABLE);
//Create table again
onCreate(sqLiteDatabase);
}
private boolean haveNetworkConnection()
{
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for(NetworkInfo ni : netInfo)
{
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
{
if(ni.isConnected())
{
haveConnectedWifi = true;
}
}
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
{
if(ni.isConnected())
{
haveConnectedMobile = true;
}
}
}
return haveConnectedWifi || haveConnectedMobile;
}
Anyone have any clues on how I can solve this?

try this
context = getApplicationContext();
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Hope it helps

Related

Using SQLite to record sensor data

I am new in Android. I am working on magnetic sensor in android phone. I am able to access the magnetic sensor and record the sensor data into the .csv file. But i want to record it in SQLite. The problem is that the magnetic sensor data can be obtained in onSensorChanged method in main activity and i dont know how to prepare insert class in SQLite which can obtain the data from the main activity. I have pasted the code for getting data and DBHelper class.
Any help will be useful . thank you in advance.
// For accessing and displaying magnetic data
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Sensor magnetometer;
SensorManager sm;
TextView magnetismx;
TextView magnetismy;
TextView magnetismz;
DBHelper dbHelper;
public float a;
public float b;
public float c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
magnetismx = (TextView) findViewById(R.id.magnetismx);
magnetismy = (TextView) findViewById(R.id.magnetismy);
magnetismz = (TextView) findViewById(R.id.magnetismz);
magnetometer = sm.getDefaultSensor(magnetometer.TYPE_MAGNETIC_FIELD);
if (magnetometer == null) {
Toast.makeText(this, "Magnetometer not available", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
a = event.values[0];
b = event.values[1];
c = event.values[2];
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetismx.setText(Float.toString(event.values[0]));
magnetismy.setText(Float.toString(event.values[1]));
magnetismz.setText(Float.toString(event.values[2]));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
// my dbHelper class
public class DBHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
private static final String COL_ID = "ID";
private static final String COLXAXIS = "X-AXIS";
private static final String TABLENAME = "MAP_COORDINATES";
private static final String COLYAXIS = "Y-AXIS";
private static final String COLZAXIS = "Z-AXIS";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLXAXIS + " INTEGER, " +
COLYAXIS + " INTEGER, " +
COLZAXIS + " INTEGER )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
public void insert(Integer x, Integer y, Integer z, SQLiteDatabase db ) {
ContentValues contentvalues = new ContentValues();
contentvalues.put("X-AXIS", x);
contentvalues.put("Y-AXIS", y);
contentvalues.put("Z-AXIS", z);
db.insert("MAP_COORDINATES", null, contentvalues);
}
}
You change your DB class as singleton like this, and change the data type Integer to REAL because you are going to store float value,
Note: "-" is not valid in sqlite name so I changed to "_", ex in X-AXIS I converted to X_AXIS.
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
private static final String COL_ID = "ID";
private static final String COLXAXIS = "X_AXIS";
private static final String TABLENAME = "MAP_COORDINATES";
private static final String COLYAXIS = "Y_AXIS";
private static final String COLZAXIS = "Z_AXIS";
private static DBHelper mInstance;
private DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static DBHelper getInstance() {
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(BaseApp.getApp());
}
}
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLXAXIS + " REAL, " +
COLYAXIS + " REAL, " +
COLZAXIS + " REAL )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
public void insert(float x, float y, float z) {
ContentValues contentvalues = new ContentValues();
contentvalues.put("X-AXIS", x);
contentvalues.put("Y-AXIS", y);
contentvalues.put("Z-AXIS", z);
getWritableDatabase().insert("MAP_COORDINATES", null, contentvalues);
}
}
If you already had BaseApplication class just ignore the below code
public class BaseApp extends Application {
private static BaseApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static Application getApp() {
return mInstance;
}
}
check you added your base class in mainfest file or not,
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:name=".BaseApp"
android:theme="#style/AppTheme">
</application>
After getting sensor data you can call like this,
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
a = event.values[0];
b = event.values[1];
c = event.values[2];
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
DBHelper.getInstance().insert(a, b, c);
}
}
Usually when working with a database helperclass you want to only have one instance of the object.
This can be realized like this:
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
....
private static DBHelper instance;
public static DBHelper getInstance (Context context) {
if (instance == null)
instace = new DBHelper (context);
return instance;
}
private DBHelper (Context context) // Notice the private constructor
....
}
....
}
Now the helper can be accessed with DBHelper.getInstance (this) from your Activity
Note: This is called a singleton pattern

Creating SQLite database for Live magnetic sensor data

I am new in Android platform. I want to record the live magnetic sensor data directly to sQLite database in storage. I wrote code to get magnetic data but i am not able to create the database. I have pasted code below. Any help would be great.
Thank you in advance.
// code for Database Helper
public class DBHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
private static final String COL_ID = "ID";
private static final String COL_XAXIS = "X-AXIS";
private static final String TABLE_NAME = "MAP_COORDINATES";
private static final String COL_YAXIS = "Y-AXIS";
private static final String COL_ZAXIS = "Z-AXIS";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_XAXIS + " INTEGER," + COL_YAXIS + " INTEGER," + COL_ZAXIS + " INTEGER" + " )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void insert(Integer xaxis, Integer yaxis, Integer zaxis){
SQLiteDatabase db = this.getWritableDatabase();
}
}
// code for getting magnetic sensor data
// Its just fragment of code
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Sensor magnetometer;
SensorManager sm;
TextView magnetismx;
TextView magnetismy;
TextView magnetismz;
DBHelper dbHelper;
public float a;
public float b;
public float c;
boolean recording = false;
boolean stoprecord = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
// I have declared some button here...
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
a = event.values[0];
b = event.values[1];
c = event.values[2];
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetismx.setText(Float.toString(event.values[0]));
magnetismy.setText(Float.toString(event.values[1]));
magnetismz.setText(Float.toString(event.values[2]));
if (!recording) {
return;
}
if(stoprecord){
return;
}
}
try {
writeToCsv(Float.toString(a), Float.toString(b), Float.toString(c));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps: The code for database is not working too.. The table is not created.
I sorted out the problem myself. There was some problem in database class. I have used the below code for database helper class.
ublic class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
//Table for measurement
private static final String ID = "id";
private static final String MAP_ID = "Mapid";
private static final String COLXAXIS = "X_AXIS";
private static final String TABLENAME = "Fingerprint";
private static final String COLYAXIS = "Y_AXIS";
private static final String COLZAXIS = "Z_AXIS";
private static final String MAPX = "X_CORD";
private static final String MAPY = "Y_CORD";
private static final String DIFF = "Diff";
private static final String FINAL = "FINAL";
private static final String KEY_FINGERPRINT_ID = "id";
private static final String KEY_MAP_NAME = "map_name";
private static final String KEY_POSITION_X = "position_x";
private static final String KEY_POSITION_Y = "position_y";
private static DBHelper mInstance;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static DBHelper getInstance() {
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(BaseApp.getApp());
}
}
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "("
+ ID + " INTEGER PRIMARY KEY,"
+ MAP_ID + " INTEGER ," +
MAPX + " INTEGER, " +
MAPY + " INTEGER, " +
COLXAXIS + " REAL, " +
COLYAXIS + " REAL, " +
COLZAXIS + " REAL, " +
FINAL + " REAL )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
public void insert(int a, int b, int c, float x, float y, float z, float d) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
contentvalues.put("Mapid", a);
contentvalues.put("X_CORD", b);
contentvalues.put("Y_CORD", c);
contentvalues.put("X_AXIS", x);
contentvalues.put("Y_AXIS", y);
contentvalues.put("Z_AXIS", z);
contentvalues.put("FINAL", d);
db.insert("Fingerprint", null, contentvalues);
db.close();
}
public void deleteAllFingerprints() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLENAME, null, null); // delete all fingerprints
db.close();
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cur = db.rawQuery("select * from " + TABLENAME, null);
return cur;
}
}

GCM message error in saving in database

Im trying to save the gcm message in database but everytime i send a message, the app closes.
Here is my GCMIntentService OnMessage method:
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("Memo");
displayMessage(context, message);
MemoDBAdapterHandler db = new MemoDBAdapterHandler(context);
db.saveMessage(message);
generateNotification(context, message);
}
Here is MemoDBAdapterHandler
public class MemoDBAdapterHandler {
public static final String KEY_BODY = "Body";
public static final String KEY_ROWID ="_id1";
private static final String TAG = "MemoDBAdapterHandler";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/** CreateMemoDatabase **/
private static final String DATABASE_CREATE =
"create table memosTable1 (KEY_BODY integer primary key autoincrement, "
+ "Body string not null);";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "GCM2";
private static final String DATABASE_TABLE = "memosTable1";
private final Context mCtx;
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) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS memosTable");
onCreate(db);
}
}
public MemoDBAdapterHandler(Context ctx)
{
this.mCtx = ctx;
}
public MemoDBAdapterHandler open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long saveMessage(String msg)
{
//SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_BODY, msg);
//mDb.close();
return mDb.insert(DATABASE_TABLE, null, cv);
}
Update your code with below
private static final String DATABASE_CREATE =
"create table memosTable1 (KEY_ROWID integer primary key autoincrement, "
+ "Body string not null);";
You were giving same column name.

Access SQLiteOpenHelper onCreate Method from wrapping class

Right now i am calling an insertSomeContacts() function in the onCreate method of the MainActivity which obviously adds the given contacts every time the app is restarted (including screen roation)...since my SQLiteOpenHelper Sub-Class is part of my ContactsDBAdapter Class (which carries the insertSomeContacts() method) - how do i get this function to execute in the SQLiteOpenHelper onCreate so that it only executes once at creation of the database?
Really having problems understanding the scope of this and passing that scope around properly.
MainActivity.java:
public class MainActivity extends Activity {
Intent intent;
private ContactsDBAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new ContactsDBAdapter(this);
dbHelper.open();
//dbHelper.deleteAll();
//dbHelper.insertSomeContacts();
displayListView();
}
private void displayListView(){
Cursor cursor = dbHelper.getAll();
String[] fromColumns = new String[]{
ContactsDBAdapter.COLUMN_TYPE,
ContactsDBAdapter.COLUMN_CLTYP,
ContactsDBAdapter.COLUMN_NAME,
ContactsDBAdapter.COLUMN_VNAME
};
int[] toViews = new int[]{
R.id.contactType,
R.id.contactCltype,
R.id.contactName,
R.id.contactVname
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor, fromColumns, toViews, 0);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(dataAdapter);
}
ContactsDBAdapter.java:
public class ContactsDBAdapter{
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_CLTYP = "cltyp";
public static final String COLUMN_MDT = "mdt";
public static final String COLUMN_OBJ = "obj";
public static final String COLUMN_VTR = "vtr";
public static final String COLUMN_FKZ = "fkz";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VNAME = "vname";
public static final String COLUMN_TEL = "tel";
public static final String COLUMN_FAX = "fax";
public static final String COLUMN_MOBIL = "mobil";
public static final String COLUMN_EMAIL = "email";
private static final String TAG = "ContactsDBAdapter";
private DBTools mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "hvkontakte.db";
private static final String DATABASE = "hvkontakte";
private static final String TABLE_NAME = DATABASE;
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TYPE + ", " + COLUMN_CLTYP + ", " + COLUMN_MDT + ", " + COLUMN_OBJ + ", "
+ COLUMN_VTR + ", " + COLUMN_FKZ + ", " + COLUMN_NAME + ", " + COLUMN_VNAME + ", "
+ COLUMN_TEL + ", " + COLUMN_FAX + ", " + COLUMN_MOBIL + ", " + COLUMN_EMAIL + ")";
private static class DBTools extends SQLiteOpenHelper{
public DBTools(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
Log.w(TAG, DATABASE_CREATE);
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS" + DATABASE);
onCreate(database);
}
}
public ContactsDBAdapter(Context ctx){
this.mCtx = ctx;
}
public ContactsDBAdapter open() throws SQLException{
mDbHelper = new DBTools(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
if(mDbHelper != null){
mDbHelper.close();
}
}
public long createContact(String type, String cltyp, String mdt, String obj, String vtr,
String fkz, String name, String vname, String tel, String fax,
String mobil, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_TYPE, type);
initialValues.put(COLUMN_CLTYP, cltyp);
initialValues.put(COLUMN_MDT, mdt);
initialValues.put(COLUMN_OBJ, obj);
initialValues.put(COLUMN_VTR, vtr);
initialValues.put(COLUMN_FKZ, fkz);
initialValues.put(COLUMN_NAME, name);
initialValues.put(COLUMN_VNAME, vname);
initialValues.put(COLUMN_TEL, tel);
initialValues.put(COLUMN_FAX, fax);
initialValues.put(COLUMN_MOBIL, mobil);
initialValues.put(COLUMN_EMAIL, email);
return mDb.insert(TABLE_NAME, null, initialValues);
}
public boolean deleteAll() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_NAME, null , null);
return doneDelete > 0;
}
public Cursor getAll() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID,
COLUMN_TYPE, COLUMN_CLTYP, COLUMN_NAME, COLUMN_VNAME},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeContacts(){
createContact("vtr","Tenant","1","82","1","2","Bennett","Tony","0911-123456","0911-123457","01577-12345678","info#email.com");
createContact("vtr","Owner","1","82","","","Smith","Brad","0911-1234567","0911-1234567","01577-84368365","info#email.com");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
//createContact("","","","","","","","","","","","");
}
}
work with SharedPreferences. Set a init boolean. if init is false insert the contacts -> set the init to true. after restarting do noting when init is true.
But this is maybe not the best solution for your usecase...

Why I am not getting any result from rawQuery method in android

I am doing a simple SQlite Apps where I want to save group name in a table and show it on a listview as soon as user click on the add button.
Can any body help me why I am not getting null value from rawQuery result?
public class AddData {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "Grup.db";
public static final int DB_VERSION = 1;
public static final String TABLE = "Grups";
public static final String C_ID = BaseColumns._ID;
public static final String C_CREATED_AT = "easy_ass_created_At";
public static final String C_NAME = "name";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper {
// public static final String TAG = DbHelper.class.getSimpleName();
// public static final String DB_NAME = "Grup.db";
// public static final int DB_VERSION = 1;
// public static final String TABLE = "Grups";
// public static final String C_ID = BaseColumns._ID;
// public static final String C_CREATED_AT = "easy_ass_created_At";
// public static final String C_NAME = "name";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = ("create table " + TABLE + " ( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null" + ");");
db.execSQL(sql);
Log.d(TAG, "OnCreate sql" + sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE);
this.onCreate(db);
Log.d("TAG", "********On Upgrate Drop Table*****");
}
}
public AddData(Context context) {
ourContext = context;
}
public AddData open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name) {
ContentValues cv = new ContentValues();
cv.put(C_NAME, name);
return ourDatabase.insert(TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { C_ID, C_NAME };
Cursor c = ourDatabase.query(TABLE, columns, null, null, null, null,
null);
String result = "";
// int iRow=c.getColumnIndex(C_ID);
int iName = c.getColumnIndex(C_NAME);
// for(c.moveToFirst();!c.isAfterLast();c.moveToLast()){
for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
.moveToNext()) {
result = result + " " + c.getString(iName) + "\n";
c.moveToNext();
}
c.close();
return result;
}
public ArrayList<String> fatchData() {
ArrayList<String> results = new ArrayList<String>();
try {
Cursor c = ourDatabase.rawQuery("SELECT * from Grups;", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("name"));
results.add("Project: " + firstName);
} while (c.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (ourDatabase != null)
ourDatabase.execSQL("DELETE FROM Grups");
ourDatabase.close();
}
return results;
}
}
Try removing c.close() and use startManagingCursor(c) (after creating the cursor) in your getData() method

Categories