I am fetching information from a SQLite database and displaying it via a list view. Above the list view i have a spinner with various options created in XML:
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:entries="#array/catergory_arrays" />
Array of spinner values:
<string-array name="catergory_arrays">
<item>Select category here:</item>
<item>Fridge / Freezer</item>
<item>Canned Food</item>
<item>Fruit</item>
<item>Vegetable</item>
</string-array>
Dependent on the position of the spinner i want to set a different query which is then shown in the listview. Current code:
Class to show database information (CurrentItems):
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
int spinnerID;
// the table that displays the data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_inventory);
db = new ItemDatabase(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
displaySearch();
}
private void setupViews() {
// bring up current database items
listView = (ListView) findViewById(R.id.dbListView);
// THE BUTTONS
addButton = (Button) findViewById(R.id.scanCurrent);
editButton = (Button) findViewById(R.id.editItemCurrent);
}
private void addButtonListeners() {
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, AddItem.class));
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, EditItems.class));
}
});
}
public int getSelectedItemPosition() {
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
return spinnerID;
}
private void displaySearch() {
// TODO Auto-generated method stub
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
String catSelected;
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> itemArray;
itemArray = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
{
if (getSelectedItemPosition() == 0) {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 1) {
catSelected = "Fridge";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 2) {
catSelected = "Can";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 3) {
catSelected = "Fruit";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 4) {
catSelected = "Vegetable";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
ItemDatabase:
package com.example.fooditemmonitor;
import java.util.ArrayList;
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 final class ItemDatabase {
// the Activity or Application that is creating an object from this class.
Context context;
// a reference to the database used by this application/object
private SQLiteDatabase db;
// These constants are specific to the database.
private final String DATABASE_NAME = "ItemDatabase.sqlite";
private final int DATABASE_VERSION = 5;
// These constants are specific to the database table.
private final String TABLE_NAME = "foodItems";
private final String COLUMN_NAME_ENTRY_ID = "entryid";
private final String COLUMN_NAME_BARCODE = "barcode";
private final String COLUMN_NAME_TITLE = "title";
private final String COLUMN_NAME_QUANTITY = "quantity";
private final String COLUMN_NAME_DATE = "date";
private final String COLUMN_NAME_CATEGORY = "category";
String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
+ COLUMN_NAME_ENTRY_ID
+ " integer primary key autoincrement not null," + COLUMN_NAME_DATE
+ " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
+ " text," + COLUMN_NAME_QUANTITY + " int," + COLUMN_NAME_CATEGORY + " text" + ");";
public ItemDatabase(Context context) {
this.context = context;
// create or open the database
ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo,
String rowStringThree, String rowStringFour, int rowIntFive) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_CATEGORY, rowStringFour);
values.put(COLUMN_NAME_QUANTITY, rowIntFive);
// ask the database object to insert the new data
try {
db.insert(TABLE_NAME, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to update the database row of given rowID
try {
db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
null);
} catch (Exception e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID) {
// ask the database manager to delete the row of given id
try {
db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
getAllRowsAsArrays();
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public ArrayList<ArrayList<Object>> getCategoryOfArrays(String category) {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, COLUMN_NAME_CATEGORY + "='" + category + "'", null,
null, null, COLUMN_NAME_TITLE + " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
while (cursor.moveToNext()) {
// your content
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CATEGORY)));
dataArrays.add(dataList);
}
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, null, null,
null, null, COLUMN_NAME_TITLE + " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
while (cursor.moveToNext()) {
// your content
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CATEGORY)));
dataArrays.add(dataList);
}
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// execute the query string to the database.
db.execSQL(SQL_CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade
// policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
}
Have tested getCategoryOfArrays() and it works. Current code doesn't return any errors however Spinner action does not change the listview contents.
All help will be appreciated!
Your method displaySearch() is only called once, at Activity creation, when the spinner is at position zero. In onCreate (perhaps within your addButtonListeners() method) set a listener on the spinner for when the value changes. When it does, call displaySearch() again.
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
selectCat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
displaySearch();
}
public void onNothingSelected(AdapterView<?> parent)
{
// Do nothing
}
});
Related
I want to create a new table in my Database (meaning I will have two tables). In that table I will only have one and only value and the use of that only value is I will get it and I will perform addition or subtraction and inserting/updating it again for the new value that has been subtracted or added values (basically it is an integer value or boolean for decimals). I'm still new at sqlite and a beginner at android development.
My Question is that how will I have/insert only one value in the table BY DEFAULT and how will I get and update it. Because when I add INSERT query in the activity itself or in the button/fab it will add new values each time I will open the fragment itself or press the button/fab. How will I have only one data in there BY DEFAULT and how to get it so I can add or subtract values in to it and update it for the new value?
I created two tables:
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_CASHFLOW_TABLE = "CREATE TABLE " + ItemEntry.TABLE_NAME2 + " (" +
ItemEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ItemEntry.COLUMN_INCOME + " INTEGER NOT NULL, " +
ItemEntry.COLUMN_SAVINGS + " INTEGER NOT NULL " +
");";
final String SQL_CREATE_ITEMLIST_TABLE = "CREATE TABLE " + ItemEntry.TABLE_NAME + " (" +
ItemEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ItemEntry.COLUMN_LABEL + " TEXT NOT NULL, " +
ItemEntry.COLUMN_DETAIL + " TEXT, " +
ItemEntry.COLUMN_AMOUNT + " INTEGER NOT NULL, " +
ItemEntry.COLUMN_DATE + " TEXT " +
");";
db.execSQL(SQL_CREATE_ITEMLIST_TABLE);
db.execSQL(SQL_CREATE_CASHFLOW_TABLE);
}
Codes I tried from bk7:
public void insertOrUpdateTheIncomeAndSavings(int income, int savings){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * from "+ItemEntry.TABLE_NAME2,null);
if(cursor.moveToNext()){
//update the values of first row here
//update income
Cursor cursor2 = sqLiteDatabase.rawQuery("UPDATE "+ItemEntry.TABLE_NAME2+" SET "+ItemEntry.COLUMN_INCOME+
" = "+ income + " WHERE "+ItemEntry._ID +" = 1",null);
}else{
//insert the value here
ContentValues cv = new ContentValues();
cv.put(ItemEntry.COLUMN_INCOME, 0);
cv.put(ItemEntry.COLUMN_SAVINGS, 0);
}
if(cursor!=null){
cursor.close();
}
sqLiteDatabase.close();
}
How can I do it in income java:
package com.example.admin.test2;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class Income extends Fragment {
public Income() {
// Required empty public constructor
}
private EditText textInput;
private FloatingActionButton fabPlus;
private FloatingActionButton fabMinus;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate (R.layout.fragment_income, container, false);
textInput = (EditText) view.findViewById(R.id.editText2);
fabPlus = (FloatingActionButton) view.findViewById(R.id.fabPlus);
fabMinus = (FloatingActionButton) view.findViewById(R.id.fabMinus);
fabPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
}
and get values from this editText:
textInput = (EditText) view.findViewById(R.id.editText2);
I want to display the input I inputted in the database in this textView but it does not work.. please check the code:
public void getIncome() {
Cursor cur = mDatabase.rawQuery("SELECT " + ItemContract.ItemEntry.COLUMN_INCOME + " as Income FROM " + ItemContract.ItemEntry.TABLE_NAME2
, null);
if (cur.moveToFirst()) {
int incomeTotal = cur.getInt(cur.getColumnIndex("Income"));// get final total
income.setText("₱ " + incomeTotal);
}
Here were inserting first row if it does not exist and updating the first row is exists.
public void insertOrUpdateTheIncomeAndSavings(int income, int savings){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from "+ItemEntry.TABLE_NAME2,null);
if(cursor.moveToNext()){
//update the values of first row here
}else{
//insert the value here
}
if(cursor!=null){
cursor.close();
}
sqLiteDatabase.close();
}
Edit: Add this in Onclick
DBHelper dbhelper = new DBHelper(getActivity());
int income = Integer.valueOf(incomeEditText.getText().toString());
int savings = Integer.valueOf(savingsEditText.getText().toString());
dbhelper.insertOrUpdateTheIncomeAndSavings(income,savings);
public void updateEmployeeName(String empNo,String new_empname) {
Cursor cursor = null;
String empName = "";
try {
cursor = SQLiteDatabaseInstance_.rawQuery("SELECT EmployeeName
FROM Employee WHERE EmpNo=?", new String[] {empNo + ""});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
empName = cursor.getString(cursor.getColumnIndex("EmployeeName"));
update(empname);
}else{
update(new_empname);
}
}finally {
cursor.close();
}
}
**Update single value use this query:-**
public void update(){
ContentValues cv = new ContentValues();
cv.put(ColumnName, newValue);
db.update(TABLE_NAME, cv, Column + "= ?", new String[] {rowId});
}
**delete single value use this query:-**
public void delete_singlevalue(String newValue) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("delete from TABLE_NAME where
ColumnName="+"'"+newValue+"'");
db.close();
}
I have a listView which displays clothing items in my shopping cart from my existing database and at the bottom it shows you the total price of all the items in my cart. When I delete items from my cart, the listView does get updated, it removes the item, but the total price that displays at the bottom does not get updated when I delete this item and this total price just comes from a query that does SUM(Price) from my table which contains my items in my cart. I've posted my some of my code below and if anyone can help, that would be great.
DatabaseHelper.java
package ankitkaushal.app.healthysizing;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DB_PATH = "/data/data/ankitkaushal.app.healthysizing/databases/";
public static String DB_NAME = "FinishDatabase";
public static final int DB_VERSION = 1;
public static final String shoppingCartTable = "OPS_insert";
private SQLiteDatabase myDB;
private Context context;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
#Override
public synchronized void close(){
if(myDB!=null){
myDB.close();
}
super.close();
}
// Retrieves all shirt and pant items of the specified brand typed into the search bar
public ArrayList<Item> getAllSearchedItems(String brand, String table_name, String size) {
if (size.equals("null")) {
brand = "\"" + brand + "\"";
ArrayList<Item> itemList = new ArrayList<Item>();
String query = "SELECT * FROM " + table_name + " WHERE Brand LIKE " + brand + " ORDER BY Price ASC"; //query to get all the shirt or pant items for brand typed in
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
else {
brand = "\"" + brand + "\"";
ArrayList<Item> itemList = new ArrayList<Item>();
String query = "SELECT * FROM " + table_name + " WHERE Brand LIKE " + brand + " AND Size = '" + size + "' ORDER BY Price ASC"; //query to get all the shirt or pant items for brand typed in
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
}
// Retrieves all shirt or pant items from the database
public ArrayList<Item> getAllItems(String table_name, String size) {
if (size.equals("null")) {
ArrayList<Item> itemList = new ArrayList<Item>();
String query = "SELECT * FROM " + table_name + " ORDER BY Price ASC"; //query to get all the shirt or pant items
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
else {
ArrayList<Item> itemList = new ArrayList<Item>();
String query = "SELECT * FROM " + table_name + " WHERE Size = '" + size + "' ORDER BY Price ASC"; //query to get all the shirt or pant items
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
}
// Retrieves all shoe items from the database
public ArrayList<Item> getAllShoes() {
ArrayList<Item> shoeList = new ArrayList<Item>();
String query = "SELECT * FROM Shoes ORDER BY Price ASC "; // query to get all shoe items
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setGender(cursor.getString(4));
item.setID(cursor.getString(5));
item.setSize("See Description");
shoeList.add(item);
} while (cursor.moveToNext());
}
return shoeList;
}
// Retrieves all shoe items of specified brand typed into the search bar
public ArrayList<Item> getAllSearchedShoes(String brand) {
brand = "\"" + brand + "\"";
ArrayList<Item> shoeList = new ArrayList<Item>();
String query = "SELECT * FROM Shoes WHERE Brand LIKE " + brand + " ORDER BY Price ASC "; //query to get all the shoes for brand typed in
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setGender(cursor.getString(4));
item.setID(cursor.getString(5));
item.setSize("See Description");
shoeList.add(item);
} while (cursor.moveToNext());
}
return shoeList;
}
// Retrieves all outerwear items from the database
public ArrayList<Item> getAllOuterwear() {
ArrayList<Item> outerwearList = new ArrayList<Item>();
String query = "SELECT * FROM Outerwear ORDER BY Price ASC "; // query to get all outerwear items
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
outerwearList.add(item);
} while (cursor.moveToNext());
}
return outerwearList;
}
// Retrieves all outerwear items of specified brand typed into the search bar
public ArrayList<Item> getAllSearchedOuterwear(String brand) {
brand = "\"" + brand + "\"";
ArrayList<Item> outerwearList = new ArrayList<Item>();
String query = "SELECT * FROM Outerwear WHERE Brand LIKE " + brand + " ORDER BY Price ASC "; //query to get all the outerwear for brand typed in
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
outerwearList.add(item);
} while (cursor.moveToNext());
}
return outerwearList;
}
// Retrieves all the items in the cart
public ArrayList<Item> getItemsInCart() {
ArrayList<Item> cartList = new ArrayList<Item>();
String query = "SELECT * FROM " + shoppingCartTable + " ORDER BY Price ASC"; // query to get all the items in the cart
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
cartList.add(item);
} while (cursor.moveToNext());
}
return cartList;
}
// Adds the item chosen from the listView to your shopping cart.
public void addToCart(Item item) {
String description = item.getDescription();
description = description.replaceAll("\"", " inch");
String brand = item.getBrand();
description = "\"" + description + "\"";
brand = "\"" + brand + "\"";
String query = "INSERT INTO " + shoppingCartTable + " (Brand, Store, Price, Description, Size, Gender, ID) " +
"VALUES (" + brand + ", '" + item.getStore() + "', '" + item.getPrice() + "', "
+ description + ", '" + item.getSize() + "', '" + item.getGender() + "', '" + item.getID() + "')";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
}
// Deletes the item from the shopping cart
public void deleteItemFromCart(String ID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(shoppingCartTable, " ID = '" + ID + "'", null);
}
// Returns total price of items in shopping cart
public String getTotalCartPrice() {
String SQLQuery = "SELECT SUM(Price) FROM OPS_insert";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String priceTotal = c.getString(0);
return priceTotal;
}
public void setLimitPants(String startSize, String currentSize, String limit) {
String SQLQuery = "UPDATE setLimitPants SET startingSize = '" + startSize + "', currentSize = '" + currentSize + "', limitSize = '" + limit + "'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(SQLQuery);
}
public String getLimit(String tableName) {
String SQLQuery = "SELECT limitSize FROM " + tableName;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String limit = c.getString(0);
return limit;
}
public void setLimitShirts(String startSize, String currentSize, String limit) {
String SQLQuery = "UPDATE setLimitShirts SET startingSize = '" + startSize + "', currentSize = '" + currentSize + "', limitSize = '" + limit + "'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(SQLQuery);
}
public String getStartSizePants() {
String SQLQuery = "SELECT startingSize FROM setLimitPants";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String startingSize = c.getString(0);
return startingSize;
}
public String getStartSizeShirts() {
String SQLQuery = "SELECT startingSize FROM setLimitShirts";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String startingSize = c.getString(0);
return startingSize;
}
public String getCurrentShirtSize() {
String SQLQuery = "SELECT currentSize FROM setLimitShirts";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String currentSize = c.getString(0);
return currentSize;
}
public String getCurrentPantsSize() {
String SQLQuery = "SELECT currentSize FROM setLimitPants";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String currentSize = c.getString(0);
return currentSize;
}
public void updateSizeShirts(String newSize) {
String SQLQuery = "UPDATE setLimitShirts SET currentSize = '" + newSize + "'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(SQLQuery);
}
public void updateSizePants(String newSize) {
String SQLQuery = "UPDATE setLimitPants SET currentSize = '" + newSize + "'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(SQLQuery);
}
public void removeLImit(String tableName) {
String SQLQuery = "UPDATE " + tableName + " SET startingSize = 'null', currentSize = 'null', limitSize = 'null'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(SQLQuery);
}
/***
* Open database
* #throws android.database.SQLException
*/
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* Copy database from source code assets to device
* #throws java.io.IOException
*/
public void copyDataBase() throws IOException {
try {
InputStream myInput = context.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e("tle99 - copyDatabase", e.getMessage());
}
}
/***
* Check if the database doesn't exist on device, create new one
* #throws IOException
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e("tle99 - create", e.getMessage());
}
}
}
// ---------------------------------------------
// PRIVATE METHODS
// ---------------------------------------------
/***
* Check if the database is exist on device or not
* #return
*/
private boolean checkDataBase() {
SQLiteDatabase tempDB = null;
try {
String myPath = DB_PATH + DB_NAME;
tempDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
Log.e("tle99 - check", e.getMessage());
}
if (tempDB != null)
tempDB.close();
return tempDB != null ? true : false;
}
}
CartItemsAdapter.java
package ankitkaushal.app.healthysizing;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public final class CartItemsAdapter extends ArrayAdapter<Item> implements View.OnClickListener {
public CartItemsAdapter(Context context, ArrayList<Item> shirtItems) {
super(context, 0, shirtItems);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Item item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.cart_layout, parent, false);
}
// Lookup view for data population
TextView brand = (TextView) convertView.findViewById(R.id.txt_cart_brand);
TextView price = (TextView) convertView.findViewById(R.id.txt_cart_price);
TextView store = (TextView) convertView.findViewById(R.id.txt_cart_store);
TextView size = (TextView) convertView.findViewById(R.id.txt_cart_size);
TextView description = (TextView) convertView.findViewById(R.id.txt_cart_description);
ImageView shirtsImage = (ImageView) convertView.findViewById(R.id.image_view_cart);
Button deleteFromCartButton = (Button) convertView.findViewById(R.id.deleteItemButton);
// Populate the data into the template view using the data object
brand.setText("Brand:" + " " + item.getBrand());
price.setText("Price:" + " $" + item.getPrice());
store.setText("Store:" + " " + item.getStore());
size.setText("Size:" + " " + item.getSize());
description.setText("Description:" + " " + item.getDescription());
Context context = parent.getContext();
try { // Find the image name from database ID column and link that up with the name of image in drawable folder
String itemName = item.getID();
String uri = "#drawable/"+itemName;
int imageResource = context.getResources().getIdentifier(uri, null, context.getApplicationContext().getPackageName());
Drawable drawable = context.getResources().getDrawable(imageResource);
shirtsImage.setImageDrawable(drawable);
}
catch (Exception e) { // If no image found for item, just set the image to a default image in drawable folder
// TODO Auto-generated catch block
Drawable drawable = context.getResources().getDrawable(R.drawable.shirts); // Default image
shirtsImage.setImageDrawable(drawable);
}
deleteFromCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// To get the item from the listView for which the Add to Cart button is pressed
Item item = getItem(position);
// Delete the item from the cart by pressing the delete item button
DatabaseHelper db = new DatabaseHelper(getContext());
db.deleteItemFromCart(item.getID());
remove(item);
// Update the listView to reflect the changes
notifyDataSetChanged();
}
});
// Return the completed view to render on screen
return convertView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
shoppingCart.java
package ankitkaushal.app.healthysizing;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
public class shoppingCart extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
final DatabaseHelper dbhelper;
final ListView listView;
final ListAdapter cartAdapter;
dbhelper = new DatabaseHelper(getApplicationContext());
try {
dbhelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
listView = (ListView) findViewById(R.id.itemsInCartList);
ArrayList<Item> cartList = dbhelper.getItemsInCart();
if (cartList != null) {
cartAdapter = new CartItemsAdapter(getApplicationContext(), cartList);
listView.setAdapter(cartAdapter);
}
listView.setEmptyView(findViewById(R.id.emptyCartMessage));
TextView displayTotalPrice = (TextView) findViewById(R.id.totalCartPrice);
String totalCartPrice = dbhelper.getTotalCartPrice();
if (totalCartPrice != null) {
displayTotalPrice.setText("Total Price: $" + totalCartPrice);
}
else {
displayTotalPrice.setText("Total Price: $0.00");
}
}
}
In my opinion, the fastest way is:
create: OnItemDeletedListener.java
OnItemDeletedListener.java
public interface OnItemDeletedListener {
public void onItemDeleted();
}
in your CartItemsAdapter add following code:
private OnItemDeletedListener onItemDeletedListener;
public void setOnItemDeletedListener(Object object) {
onItemDeletedListener = (OnItemDeletedListener) object;
}
In function getView(...) replace setOnClickListener with this:
deleteFromCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// To get the item from the listView for which the Add to Cart button is pressed
Item item = getItem(position);
// Delete the item from the cart by pressing the delete item button
DatabaseHelper db = new DatabaseHelper(getContext());
db.deleteItemFromCart(item.getID());
remove(item);
// Update the listView to reflect the changes
notifyDataSetChanged();
onItemDeletedListener.onItemDeleted();
}
Change shoppingCart class:
shoppingCart.java
package ankitkaushal.app.healthysizing;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
public class shoppingCart extends ActionBarActivity implements OnItemDeletedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
final DatabaseHelper dbhelper;
final ListView listView;
final ListAdapter cartAdapter;
dbhelper = new DatabaseHelper(getApplicationContext());
try {
dbhelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
listView = (ListView) findViewById(R.id.itemsInCartList);
ArrayList<Item> cartList = dbhelper.getItemsInCart();
if (cartList != null) {
cartAdapter = new CartItemsAdapter(getApplicationContext(), cartList);
cartAdapter.setOnItemDeletedListener(this);
listView.setAdapter(cartAdapter);
}
listView.setEmptyView(findViewById(R.id.emptyCartMessage));
displayTotalPrice();
}
private void displayTotalPrice() {
TextView displayTotalPrice = (TextView) findViewById(R.id.totalCartPrice);
String totalCartPrice = dbhelper.getTotalCartPrice();
if (totalCartPrice != null) {
displayTotalPrice.setText("Total Price: $" + totalCartPrice);
}
else {
displayTotalPrice.setText("Total Price: $0.00");
}
}
#Override
public void onItemDeleted() {
displayTotalPrice();
}
}
[EDIT]
Replace final ListAdapter cartAdapter; with final CartItemsAdapter cartAdapter;
It seems like you don't notify displayTotalPrice when you click the delete button (if this is the TextView that you want to update when you delete an item from your cart). Your activity should listen to the changes made in your CartItemsAdapter.
Add this inner interface to your CartItemsAdapter.
public static interface ItemDeleteListener {
public void onItemDelete(double price);
}
Then make a reference to this interface inside of your CartItemsAdapter:
ItemDeleteListener itemDeleteListener;
This variable should be initialized when you're creating new CartItemsAdapter (pass it as an argument):
// 'this' in this case is your Activity passed into Adapter as an argument
cartAdapter = new CartItemsAdapter(getApplicationContext(), cartList, this);
In your CartItemsAdapter constructor then initialize that interface:
this.itemDeleteListener = listener;
Then let your shopping cart Activity implement this interface:
public class shoppingCart extends ActionBarActivity implements CartItemsAdapter.ItemDeleteListener {
...
#Override
public void onItemDelete(doublePrice) {
// here you notify displayTotalPrice, doublePrice should be total price
displayTotalPrice.setText(doublePrice);
}
}
When change happens, invoke it in your CartItemsAdapter like this:
itemDeleteListener.onItemDelete(db.getTotalCartPrice());
I have two classes:
Database class:
package com.qstra.soamazingtodoapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; // used for logging database
// version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DATE = "date";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_TASK,
KEY_DATE, KEY_HOUR, KEY_MINUTE };
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
public static final int COL_HOUR = 3;
public static final int COL_MINUTE = 4;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be
// incremented each time a
// change to DB structure
// occurs.
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT" + KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT" + ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String task, String date, String hour, String minute) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String task, String date, String hour, String minute) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TASK, task);
newValues.put(KEY_DATE, date);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_MINUTE, minute);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity class:
package com.qstra.soamazingtodoapp;
import com.qstratwo.soamazingtodoapp.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
Time today = new Time(Time.getCurrentTimezone());
DBAdapter myDb;
EditText etTasks;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
String string_hour_x, string_minute_x="None";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTasks = (EditText) findViewById(R.id.editText1);
openDB();
listViewItemClick();
listViewItemLongClick();
populateListView();
// setNotification();
}
#Override
protected Dialog onCreateDialog(int idD){
if (idD== DIALOG_ID){
return new TimePickerDialog(MainActivity.this, kTimePickerListener, hour_x,minute_x, false);
}
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x=hourOfDay;
minute_x=minute;
string_hour_x = Integer.toString(hour_x);
string_minute_x = Integer.toString(minute_x);
Toast.makeText(MainActivity.this, hour_x+" : "+ minute_x,Toast.LENGTH_LONG).show();
}
};
public void setNotification(View v) {
showDialog(DIALOG_ID);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_AddTask (View v) {
today.setToNow();
String timestamp = today.format("%Y-%m-%d %H:%m:%s");
if(!TextUtils.isEmpty(etTasks.getText().toString())) {
myDb.insertRow(etTasks.getText().toString(),timestamp,string_hour_x, string_minute_x);
}
populateListView();
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
String[] fromFieldNames=new String[] {
DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK };
int[] toViewIDs = new int[] {
R.id.textViewItemNumber, R.id.textViewItemTasks};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setAdapter(myCursorAdapter);
}
private void updateTask(long id){
Cursor cursor = myDb.getRow(id);
if (cursor.moveToFirst()){
String task = etTasks.getText().toString(); // POBIERANIE Z TEXTFIELD
today.setToNow();
String date = today.format("%Y-%m-%d %H:%m");
// String string_minute_x= Integer.toString(minute_x);
// String string_houte_x=Integer.toString(hour_x);
myDb.updateRow(id, task, date, string_hour_x, string_minute_x );
}
cursor.close();
}public void onClick_DeleteTasks(View v) {
myDb.deleteAll();
populateListView();
}
public void onClick_AppClose(View v) {
moveTaskToBack(true);
MainActivity.this.finish();
}
public void listViewItemLongClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
myDb.deleteRow(id);
populateListView();
return false;
}
});
}
private void listViewItemClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
updateTask(id);
populateListView();
displayToast(id);
}
});
}
private void displayToast(long id){
Cursor cursor = myDb.getRow(id);
if(cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String task = cursor.getString(DBAdapter.COL_TASK);
String date = cursor.getString(DBAdapter.COL_DATE);
String message = "ID: " + idDB + "\n" + "Task: " + task + "\n" + "Date: " + date;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
(getting id and text from texfield to database works fine but..)
I'm trying to get hour and minutes values from TimePickerDialog and insert in to database but it seems not working.
Screen shot from log cat:
Why can't it see column named 'hour'?
Add commas in your statement to create database
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT," + KEY_HOUR + " TEXT,"
+ KEY_MINUTE + " TEXT" + ")";
I have a working sqlite database which items can be added to and viewed via a listview. I now want to add a edit/delete button to each view dynamically.
Following the tutorial http://looksok.wordpress.com/2012/11/03/android-custom-listview-tutorial/ I have created a custom XML file with an edit/delete button. I am however unable to follow the tutorial as it does not show for retrieving and displaying sqlite information.
XML layout for custom list view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText
android:id="#+id/itemName"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="2"
android:gravity="center_vertical"
android:hint="#string/title"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/itemQuantity"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:inputType="numberDecimal"
android:text="#string/quantity"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageButton
android:id="#+id/editItem"
android:layout_width="#dimen/width_button"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name"
android:onClick="editOnClick"
android:src="#android:drawable/ic_menu_edit" />
<ImageButton
android:id="#+id/deleteItem"
android:layout_width="#dimen/width_button"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name"
android:onClick="removeOnClick"
android:src="#android:drawable/ic_menu_delete" />
</LinearLayout>
Current Inventory XML (Where listview is shown):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/currentInventory"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
xmlns:tools="http://schemas.android.com/tools" >
<TextView android:layout_marginTop="5dip"
android:id="#+id/selectCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/selectCategory"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/catergory_arrays" />
<ListView
android:id="#+id/customDbListView"
android:layout_width="match_parent"
android:layout_height="350dip"
android:layout_marginBottom="20dip"
android:layout_marginTop="20dip"
tools:listitem="#layout/list_view_custom" >
</ListView>
<Button
android:id="#+id/scanCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="5dip"
android:text="#string/scan" />
<Button
android:id="#+id/editItemCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:text="#string/editItem" />
</LinearLayout>
Creation of database:
package com.example.fooditemmonitor;
import java.util.ArrayList;
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 final class ItemDatabase {
// the Activity or Application that is creating an object from this class.
Context context;
// a reference to the database used by this application/object
private SQLiteDatabase db;
// These constants are specific to the database.
private final String DATABASE_NAME = "ItemDatabase.sqlite";
private final int DATABASE_VERSION = 7;
// These constants are specific to the database table.
private final String TABLE_NAME = "foodItems";
private final String COLUMN_NAME_ENTRY_ID = "entryid";
private final String COLUMN_NAME_BARCODE = "barcode";
private final String COLUMN_NAME_TITLE = "title";
private final String COLUMN_NAME_QUANTITY = "quantity";
private final String COLUMN_NAME_DATE = "date";
private final String COLUMN_NAME_CATEGORY = "category";
String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
+ COLUMN_NAME_ENTRY_ID
+ " integer primary key autoincrement not null," + COLUMN_NAME_DATE
+ " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
+ " text," + COLUMN_NAME_QUANTITY + " int," + COLUMN_NAME_CATEGORY
+ " text" + ");";
public ItemDatabase(Context context) {
this.context = context;
// create or open the database
ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo,
String rowStringThree, String rowStringFour, int rowIntFive) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_CATEGORY, rowStringFour);
values.put(COLUMN_NAME_QUANTITY, rowIntFive);
// ask the database object to insert the new data
try {
db.insert(TABLE_NAME, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to update the database row of given rowID
try {
db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
null);
} catch (Exception e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID) {
// ask the database manager to delete the row of given id
try {
db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
getAllRowsAsArrays();
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public ArrayList<ArrayList<Object>> getCategoryOfArrays(String category) {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY,
COLUMN_NAME_CATEGORY }, COLUMN_NAME_CATEGORY + "='"
+ category + "'", null, null, null, COLUMN_NAME_TITLE
+ " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor
.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor
.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor
.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataArrays.add(dataList);
} while (cursor.moveToNext());
}
// let java know that you are through with the cursor.
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_TITLE,
COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, null, null,
null, null, COLUMN_NAME_TITLE + " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor
.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor
.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataArrays.add(dataList);
} while (cursor.moveToNext());
}
// let java know that you are through with the cursor.
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// execute the query string to the database.
db.execSQL(SQL_CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade
// policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
}
Current code to display database data:
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
int spinnerID;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_inventory);
db = new ItemDatabase(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
// display search results
displaySearch();
}
private void setupViews() {
// bring up current database items
listView = (ListView) findViewById(R.id.customDbListView);
// THE BUTTONS
addButton = (Button) findViewById(R.id.scanCurrent);
editButton = (Button) findViewById(R.id.editItemCurrent);
}
private void addButtonListeners() {
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
selectCat
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
displaySearch();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing
}
});
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, AddItem.class));
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, EditItems.class));
}
});
}
public int getSelectedItemPosition() {
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
return spinnerID;
}
private void displaySearch() {
// TODO Auto-generated method stub
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
String catSelected;
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> itemArray;
itemArray = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
{
if (getSelectedItemPosition() == 0) {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nTitle: " + row.get(0).toString()
+ "\nQuantity: " + row.get(1).toString() + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 1) {
catSelected = "Fridge";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 2) {
catSelected = "Can";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 3) {
catSelected = "Fruit";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 4) {
catSelected = "Vegetable";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nTitle: " + row.get(0).toString()
+ "\nQuantity: " + row.get(1).toString() + "\n");
itemArray.notifyDataSetChanged();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
The current code as it stands will only display the data as a regular listview. I need the data to show as:
Title Quantity (EditButton) (DeleteButton)
All help will be appreciated!
Thanks
As i was a little bored i took the liberty to implement the adapter. You will have to edit the way you retrieve your elements from the db and how the Classes Information is Accessed since you didnt post the corresponding class representation.
You could however implement a CursorAdapter instead of a BaseAdapter.
public class QuantatiyAdapter extends BaseAdapter {
private Context context;
private List<Item> data;
public QuantatiyAdapter(Context context) {
this.context = context;
//TODO actually put all your data into that list.
this.data = Database.getAllData();
}
#Override
public int getCount() {
return this.data.size();
}
#Override
public Object getItem(int arg0) {
return this.data.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View converView, ViewGroup container) {
ViewHolder holder = null;
if (converView == null) {
converView = LayoutInflater.from(context).inflate(R.layout.cutomLayout, null);
holder = new ViewHolder();
holder.title = (TextView) converView.findViewById(R.id.itemName);
holder.quantity = (TextView) converView.findViewById(R.id.itemQuantity);
holder.edit = (ImageButton) converView.findViewById(R.id.editItem);
holder.delete = (ImageButton) converView.findViewById(R.id.deleteItem);
converView.setTag(holder);
} else {
holder = (ViewHolder) converView.getTag();
}
// filling text
holder.title.setText(getItem(position).getTitle());
// adding action listeners to buttons
holder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO fill methods for buttons
}
});
return converView;
}
private static class ViewHolder {
TextView title,quantity;
ImageButton edit,delete;
}
}
I want to know how to check for duplicated fields in my database by updating it.
If the day and hour are the same in another row it must give an error.
DBHelper:
package me.wouter.schoolwork;
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 Schedule {
public static final String KEY_ROWID = "_id"; //Row Id
public static final String KEY_HOUR = "schedule_hour";
public static final String KEY_DAY = "schedule_day";
public static final String KEY_LOCATION = "schedule_location";
public static final String KEY_SUBJECT = "schedule_subject";
public static final String KEY_START = "schedule_start";
public static final String KEY_END = "schedule_end";
private static final String DATABASE_NAME = "PlanYourDay";
private static final String DATABASE_TABLE = "schedule";
private static final int DATABASE_VERSION = 1;
private dBHelper classHelper;
private final Context classContext;
private SQLiteDatabase classDatabase;
public Cursor c;
private static class dBHelper extends SQLiteOpenHelper {
public dBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_DAY + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_SUBJECT + " TEXT NOT NULL, " +
KEY_START + " TEXT NOT NULL, " +
KEY_END + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Schedule(Context c){
classContext = c;
}
public Schedule open() throws SQLException{
classHelper = new dBHelper(classContext);
classDatabase = classHelper.getWritableDatabase();
return this;
}
public Schedule close(){
classHelper.close();
return this;
}
public long createEntry(String subject, String day, String hour,
String location, String start, String end) {
ContentValues cv = new ContentValues();
cv.put(KEY_SUBJECT, subject);
cv.put(KEY_DAY, day);
cv.put(KEY_HOUR, hour);
cv.put(KEY_LOCATION, location);
cv.put(KEY_START, start);
cv.put(KEY_END, end);
return classDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_SUBJECT, KEY_HOUR, KEY_DAY, KEY_LOCATION, KEY_START, KEY_END};
c = classDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
final int iSubject = c.getColumnIndex(KEY_SUBJECT);
int iHour = c.getColumnIndex(KEY_HOUR);
int iDay = c.getColumnIndex(KEY_DAY);
int iLocation = c.getColumnIndex(KEY_LOCATION);
int iStart = c.getColumnIndex(KEY_START);
int iEnd = c.getColumnIndex(KEY_END);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iSubject) + " " + c.getString(iHour) + " "
+ c.getString(iDay) + " " + c.getString(iLocation) + " " + c.getString(iStart) + " "
+ c.getString(iEnd) + "\n";
}
return result;
}
}
DB Inserter:
package me.wouter.schoolwork;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ScheduleTest extends Activity implements OnClickListener {
// object variables
Button bLoadSql, bSaveSql;
TextView viewSubject, viewDay, viewHour, viewLocation, viewStart, viewEnd;
EditText editSubject, editDay, editHour, editLocation, editStart, editEnd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sql);
allTheVariables();
bLoadSql.setOnClickListener(this);
bSaveSql.setOnClickListener(this);
}
private void allTheVariables() {
// defines variables in xml file
// buttons
bLoadSql = (Button) findViewById(R.id.bLoadSql);
bSaveSql = (Button) findViewById(R.id.bSaveSql);
// textviews
viewSubject = (TextView) findViewById(R.id.viewSubject);
viewDay = (TextView) findViewById(R.id.viewDay);
viewHour = (TextView) findViewById(R.id.viewHour);
viewLocation = (TextView) findViewById(R.id.viewLocation);
viewStart = (TextView) findViewById(R.id.viewStart);
viewEnd = (TextView) findViewById(R.id.viewEnd);
// edittext
editSubject = (EditText) findViewById(R.id.editSubject);
editDay = (EditText) findViewById(R.id.editDay);
editHour = (EditText) findViewById(R.id.editHour);
editLocation = (EditText) findViewById(R.id.editLocation);
editStart = (EditText) findViewById(R.id.editStart);
editEnd = (EditText) findViewById(R.id.editEnd);
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bLoadSql:
Intent i = new Intent("me.wouter.schoolwork.SCHEDULEVIEW");
startActivity(i);
break;
case R.id.bSaveSql:
boolean didItWork = true;
try{
String subject = editSubject.getText().toString();
String day = editDay.getText().toString();
String hour = editHour.getText().toString();
String location = editLocation.getText().toString();
String start = editStart.getText().toString();
String end = editEnd.getText().toString();
Schedule entry = new Schedule(this);
entry.open();
entry.createEntry(subject, day, hour, location, start, end);
entry.close();
}catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Failed");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(didItWork){
Dialog d = new Dialog(this);
d.setTitle("Inserted");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
}
}
}
And Viewer/Loader:
package me.wouter.schoolwork;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ScheduleView extends Activity {
TextView subject;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
subject = (TextView) findViewById(R.id.subject);
Schedule info = new Schedule(this);
info.open();
String data = info.getData();
subject.setText(data);
info.close();
}
}
Thanks in advance!
It seems to me that what you need is a multi-column uniqueness constraint on your DB schema, with a suitable conflict clause:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_HOUR + " TEXT NOT NULL, " +
KEY_DAY + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_SUBJECT + " TEXT NOT NULL, " +
KEY_START + " TEXT NOT NULL, " +
KEY_END + " TEXT NOT NULL, " +
"UNIQUE (" + KEY_DAY + ", " + KEY_HOUR + ") ON CONFLICT ROLLBACK);"
);
This will generate a constraint violation error if the day/hour combination is not unique, without you having to write an explicit check.