Am I using Cursor properly with SQLite? - java

I'm "experimenting" with Android Studio and SQLite for the first time. My app screen turns white and freezes upon opening new activity which should show up my SQL query values.
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper (Context context) {
super(context,"book.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table books (ID INTEGER NOT NULL PRIMARY KEY, " +
"BOOK_TITLE TEXT NOT NULL, BOOK_CATEGORY TEXT NOT NULL, " +
"BOOK_DESCRIPTION TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists books");
onCreate(db);
}
public boolean insertData(String book_title_, String book_category_, String book_description_)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put("BOOK_TITLE", book_title_);
cValues.put("BOOK_CATEGORY", book_category_);
cValues.put("BOOK_DESCRIPTION", book_description_);
long result = db.insert("book", null, cValues);
if (result == -1)
return false;
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM book", null);
return res;
}
}
I found out that the problem is in calling getAllData() fuction from another class. By my logic everything should work fine? I though that the problem is in my QUERY but according to google I've done everything good.
Any suggestions?

Try this method. It's very efficient method:
public List<Movie> getAllData()
{
List<Movie> movies_list = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM movie_collection", null);
while(res.moveToNext())
{
movies_list.add(new Movie(res.getString(1)+"\n", res.getString(2)+"\n", res.getString(3)+"\n", R.drawable.gladiator));
}
res.close();
return movies_list;
}
and in viewAll() method:
public void viewAll()
{
movies_list = movie_database.getAllData();
// do whatever you want
}

Related

SQLite wont drop table

Hello I want to implement a simple survey. I successfully added the questions with an insert query. The Questions however get added every time when I run the application.
I tried to use "Drop table if exists" but nothing happens.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME= "Questionpool.db";
public static final String createdb = "Create table dtaquestions( questionId Integer Primary Key Autoincrement, dtaQuestion Varchar(100), dtaDepartment Varchar(100))";
public static final String dropdb = "Drop table if exists dtaquestions";
Context context;
public DatabaseHelper(Context context) {
super(context, DBNAME , null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createdb);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(dropdb);
}
And in the Survey class I have this,
myDb = new DatabaseHelper(this);
SQLiteDatabase DB2=myDb.getWritableDatabase();
insertQuestions(DB2);
final Cursor res = getAllData(DB2);
bViewAll = (Button) findViewById(R.id.bViewAll);
bViewAll.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
if(res.getCount()== 0){
tv.setText("nooo");
}else{
int counter = 0;
while(res.moveToNext()){
//show on screen
}
}
}
});
public void insertQuestions(SQLiteDatabase db){
String [] dtaQuestions = fillArray();
String [] dtaQuestionsDep = fillDepartment();
for (int i = 0 ; i < 18 ; i++ ){
ContentValues cv = new ContentValues();
cv.put("dtaQuestion", dtaQuestions[i]);
cv.put("dtaDepartment", dtaQuestionsDep[i]);
db.insert("dtaquestions", null, cv);
}
}
public Cursor getAllData(SQLiteDatabase db){
Cursor res = db.rawQuery("Select * from dtaquestions", null);
return res;
}
I have no idea why the drop query isn't working and the query keeps repeating itself.
Read de cocumentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
When you create the helper the version is always 1.
super(context, DBNAME , null, 1);
You need to change the version.
You can declare the version and then use it:
private static final int VERSION=2;
public DatabaseHelper(Context context) {
super(context, DBNAME , null,VERSION);
this.context = context;
}

Android Studio, how to retrieve data from Sqlite database and display it into textview?

I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball 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 balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}

How to resolve index out of bounds error with SQLite?

I'm trying to get data from SQLite databse and when I'm trying, my app crashes and the error is: "android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1".
What am I doing wrong?
This is my activity:
public class EventInfo extends AppCompatActivity {
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_info);
myDb=new DatabaseHelper(this);
SharedPreferences sp = getSharedPreferences("key", 0);
final String event_title=sp.getString("event_title", "");
final String event_date=sp.getString("event_date", "");
String event_content=sp.getString("event_content","");
String age_limit=sp.getString("age_limit","");
String event_hour=sp.getString("event_hour","");
String location_left=sp.getString("location_left","");
String location_right=sp.getString("location_right","");
TextView txt5=(TextView)findViewById(R.id.textView5);
TextView txt6=(TextView)findViewById(R.id.textView6);
TextView txt7=(TextView)findViewById(R.id.textView7);
TextView txt8=(TextView)findViewById(R.id.textView8);
TextView txt9=(TextView)findViewById(R.id.textView9);
TextView txt10=(TextView)findViewById(R.id.textView10);
TextView txt14=(TextView)findViewById(R.id.textView14);
txt5.setText(event_title);
txt6.setText(event_date);
txt7.setText(age_limit);
txt8.setText(event_content);
txt9.setText(event_hour);
txt10.setText("Press here for event location");
String votes_count=myDb.getVotesCount(event_title);
if(votes_count.equals("1")) {
txt14.setText("Cancel Attending");
}
else {
if(votes_count.equals("0")||votes_count.isEmpty()) {
txt14.setText("Accept Attending");
}
else
{
txt14.setText("Error");
}
}
txt10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventInfo.this, MapsActivity3.class);
startActivity(intent);
}
});
txt14.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String votes_count=myDb.getVotesCount(event_title);
if(votes_count.equals("0")||votes_count.isEmpty()) {
boolean insert = myDb.insertData("1", event_title, event_date);
if (insert == true)
Toast.makeText(EventInfo.this, "You have accepted the arrival", Toast.LENGTH_LONG).show();
else
Toast.makeText(EventInfo.this, "Error", Toast.LENGTH_LONG).show();
}
else
{
if(votes_count.equals("1"))
{
boolean insert = myDb.insertData("0", event_title, event_date);
if (insert == true)
Toast.makeText(EventInfo.this, "You have canceled the arrival", Toast.LENGTH_LONG).show();
else
Toast.makeText(EventInfo.this, "Error, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(EventInfo.this, votes_count.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}
And this is my DatabaseHelper Class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="usersDB.db";
public static final String TABLE_NAME="votes_table";
public static final String COL2="VOTESCOUNT";
public static final String COL3="EVENTTITLE";
public static final String COL4="EVENTDATE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (VOTESCOUNT TEXT, EVENTTITLE TEXT, EVENTDATE 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 votes_count, String event_title, String event_date){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COL2,votes_count);
contentValues.put(COL3,event_title);
contentValues.put(COL4, event_date);
long result=db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
{
return false;
}
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getEventTitles()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select EVENTTITLE from "+TABLE_NAME,null);
return res;
}
public Cursor getEventDate(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select EVENTDATE from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
return res;
}
public String getVotesCount(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
String votes_count=res.getString(0);
return votes_count;
}
}
You have to move the Cursor to the first row before you access data from it, and it's a good idea to check the return value of moveToFirst() as well to make sure that the Cursor has data. Also, be sure to close any Cursor when you're done with it:
public String getVotesCount(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
String votes_count = null;
if (res.moveToFirst()) {
votes_count =res.getString(0);
}
res.close();
return votes_count;
}
And add a null check for the return value:
String votes_count = myDb.getVotesCount(event_title);
if(votes_count != null && (votes_count.equals("0")||votes_count.isEmpty())) {
//...............

android: showing data from sqlite to AlertDialog

I'm having problem with my codes. I created 2 tables in android sqlite and I like to show the data from the database using AlertDialog but when I click the view Button it will go back to the previous activity. please check my codes. thank you
My DatabaseHelper :
private static final String TABLE_CREATE_QUIZ = "create table quiz (QUIZ_ID integer primary key not null ,"+
"question text not null, answer1 text not null, answer2 text not null, answer3 text not null, answer4 text not null);";
public DatabaseHelper(Context context)
{
super(context , DATABASE_NAME , null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
db.execSQL(TABLE_CREATE_QUIZ);
this.db = db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
String query1 = "DROP TABLE IF EXISTS "+TABLE_CREATE_QUIZ;
db.execSQL(query);
db.execSQL(query1);
this.onCreate(db);
}
public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query , null);
int count = cursor.getCount();
values.put(COLUMN_ID , count);
values.put(COLUMN_NAME , c.getName());
values.put(COLUMN_EMAIL , c.getEmail());
values.put(COLUMN_UNAME, c.getUname());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public boolean insertQuest(String question, String answer1, String answer2, String answer3, String answer4){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String query1 = "select * from quiz";
Cursor cursor = db.rawQuery(query1 , null);
int count = cursor.getCount();
contentValues.put(COLUMN_QUIZ_ID, count);
contentValues.put(COLUMN_QUESTION, question);
contentValues.put(COLUMN_ANSWER1, answer1);
contentValues.put(COLUMN_ANSWER2, answer2);
contentValues.put(COLUMN_ANSWER3, answer3);
contentValues.put(COLUMN_ANSWER4, answer4);
long result = db.insert(TABLE_QUIZ, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData(){
db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from"+TABLE_QUIZ,null);
return res;
}
My Viewing codes:
public void viewAll(){
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = helper.getAllData();
if(res.getCount()== 0){
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()){
buffer.append("Id:"+ res.getString(0)+"\n");
buffer.append("Question:"+ res.getString(1)+"\n");
buffer.append("Answer1:"+ res.getString(2)+"\n");
buffer.append("Answer2:"+ res.getString(3)+"\n");
buffer.append("Answer3:"+ res.getString(4)+"\n");
buffer.append("Answer4:"+ res.getString(5)+"\n\n");
}
showMessage("Data",buffer.toString());
}
});
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
You should probably drop TABLE_QUIZ instead of TABLE_CREATE_QUIZ if that is the table name.
But your problem lays in the fact you are missing a space between from and TABLE_QUIZ in your getAllData method.

Delete an Item on Listview but this doesnt deleted from SQLite

I use this method to delete an Item on my SQLite database:
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
And this to my ListView:
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
The problem is that when i delete an item on my listview the item disappears but when I re-open it the item is still there, because this doesn't remove from the database.
I 'll try to explain this with images :
This means that there is some problem with the deleting from the db. Just replace 2nd line in your deleteItem() with
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item}
Log.d("deletedItem", x);
Here x would be the number of rows deleted. Check the value of x after deleting, it should be greater than 0 if the deletion was successful. If it is not then that means the query is wrong and we would need the database schema for correcting it. From your ListView implementation code, its clear that your nameString itself is wrong. You are adding the whole Item in the arraylist and passing to the adapter. And when you fetch the item in the onItemClick dialog, you are using this code
String nameString = (arg0
.getItemAtPosition(arg2))
.toString();
Here arg0.getItemAtPosition(arg2) would return an Item object. You will have to do something like this.
Item tempItem=(Item)items.get(arg2);
String nameString=tempItem.getName();
where getName() would return the name of the item.
The change that I did:
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
to
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
String nameStringData = nameString.substring(6,
nameString.indexOf("Priority Level:") - 1);
Log.d("itemtodelete", nameStringData);
db.deleteItem(nameStringData);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
If you have a better suggestion please post an answer.
Yes this is the problem.
deletedItem = 0 on logCat so that's my database:
public class DatabaseHolder extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ItemsList";
private static final String TABLE_NAME = "Items";
private static final String ITEMS_COLUMN = "items_name";
private static final String PRIORITY_COLUMN = "Priority";
private static final String ID_COLUMN = "Items";
private static int DATABASE_VERSION = 1;
private static String QUERY = "CREATE TABLE " + TABLE_NAME + "("
+ ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEMS_COLUMN
+ " TEXT NOT NULL, " + PRIORITY_COLUMN + " TEXT NOT NULL);";
public DatabaseHolder(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
// Sharer!
public void addItem(String item_name, String priority) {
if (!duplicate(item_name)) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ITEMS_COLUMN, item_name);
values.put(PRIORITY_COLUMN, priority);
db.beginTransaction();
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
public boolean duplicate(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, ITEMS_COLUMN + " =?",
new String[] { name }, null, null, null);
int temp = c.getCount();
c.close();
db.close();
if (temp > 0)
return true;
else
return false;
}
public ArrayList<Item> getAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Item> item = new ArrayList<Item>();
db.beginTransaction();
Cursor cursor = db.query(TABLE_NAME, new String[] { this.ITEMS_COLUMN,
this.PRIORITY_COLUMN }, null, null, null, null, PRIORITY_COLUMN
+ " DESC");
while (cursor.moveToNext()) {
Item itemTemp = new Item(cursor.getString(cursor
.getColumnIndexOrThrow(ITEMS_COLUMN)), new Level(
Integer.parseInt(cursor.getString(cursor
.getColumnIndexOrThrow(PRIORITY_COLUMN)))));
item.add(itemTemp);
}
cursor.close();
db.endTransaction();
db.close();
return item;
}
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
Log.d("deletedItem", String.valueOf(x) );
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}

Categories