Reputation: 124
Im trying to use SQLite database in AsyncTask but i dont know how to initialize it in this class. Can anyone help me please? If anyone has any advice I'd appreciate it.
public class ReadRssBackground extends AsyncTask<Context, Void, Void> {
DatabaseHelper myDB;
@Override
protected Void doInBackground(Context... contexts) {
myDB = new DatabaseHelper(context); // <--- how to do it right?
checkXML(GetData());
return null;
}
public void checkXML(Document data) {
//here i try do read or write a new item in the DB
myDB.insertData("2", "Tittel", "www.link.de","Stuff");
}
public Document GetData() {
//here i get the document from a url
}
}
And here is my DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "title.db";
public static final String TABLE_NAME = "feed_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "TITLE";
public static final String COL_3 = "LINK";
public static final String COL_4 = "CATEGORY";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.e
xecSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,TITLE TEXT,LINK TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String id,String title, String link, String category){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,title);
contentValues.put(COL_3,link);
contentValues.put(COL_4,category);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result==(-1))
return false;
else
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[]{id});
}
}
Upvotes: 0
Views: 5614
Reputation: 91
Find the below code snippet for SQLite initialization in AsyncTask.
DatabaseHelper myDB;
public class ReadRssBackground extends AsyncTask<Context, Void, Void> {
@Override
protected void onPreExecute() {
myDB = new DatabaseHelper(context);
}
@Override
protected void doInBackground(Context... contexts) {
checkXML(GetData());
return null;
}
}
public void checkXML(Document data) {
myDB.insertData("2", "Tittel", "www.link.de","Stuff");
}
public Document GetData() {
//here i get the document from a url
}
Upvotes: 2
Reputation: 426
Create a constructor in ReadRssBackground and pass application context and store it. (can use getApplicationContext() inside activity) Use this context in new DatabaseHelper(context)
Upvotes: 0