Android ListView not displaying database information - java

Attached above is a screenshot of the issue. Will not update with information of the database:
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:entries="#array/catergory_arrays"
android:gravity="right" />
<ListView
android:id="#+id/dbListView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="10dip" >
</ListView>
<Button
android:id="#+id/scanCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dip"
android:text="#string/scan" />
<Button
android:id="#+id/editItemCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="10dp"
android:text="#string/editItem" />
</LinearLayout>
CurrentItems - Should be displaying current database rows
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
// 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));
}
});
}
private void displaySearch() {
// TODO Auto-generated method stub
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate:" + row.get(0).toString() + " Title:"
+ row.get(1).toString() + "\n" + "Quantity:"
+ Integer.parseInt(row.get(2).toString()) + "\n");
aa.notifyDataSetChanged();
}
listView.setAdapter(aa);
}
#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);
}
}
ItemsDatabase
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 = 3;
// 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";
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" + ");";
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, 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 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);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
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 }, null, null,
null, null, COLUMN_NAME_TITLE + " DESC");
// 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.getColumnIndex(COLUMN_NAME_DATE));
dataList.add(cursor.getColumnIndex(COLUMN_NAME_TITLE));
dataList.add(cursor.getColumnIndex(COLUMN_NAME_QUANTITY));
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);
}
}
}
No errors are thrown in the logcat. Should display data in order of Date, Title and then Quantity.
All help will be appreciated.

cursor.getColumnIndex
returns the index of a column by name. So you have indexes as a result. You should do something like:
dataList.add(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));

Related

how to make a search in a list view android which is populated from SQLite database

Hi to everyone I am new to android just a beginner. I am developing an app which shows a list of medicine with the brand name and generic name. I am using ListView for displaying data and this data is coming from SQLite database. What I want when a user enters a name of a medicine in a editText it should show the search result from the ListView like for example my List has a medicine name NICOX a brand name. And user wants to search this name and Enters N in the edit text then this name should be shown in the list view and all other names which start form the letter which the user enters in the edit text I added all my code here is my Main Activity code.
package com.example.clnicmangmentapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
import com.example.clnicmangmentapp.data.AddNewProductDataBaseHelper;
public class MainActivity extends AppCompatActivity {
AddNewProductDataBaseHelper mDataBaseHelper;
SQLiteDatabase database;
Cursor cursor;
SearchView mSearchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchView = findViewById(R.id.search_view);
mDataBaseHelper = new AddNewProductDataBaseHelper(this);
database = mDataBaseHelper.getWritableDatabase();
cursor = database.rawQuery("SELECT * FROM " + AddNewProductEntry.TABLE_NAME, null);
ListView listView = findViewById(R.id.list_view);
DispalyDataAdapterView adapter = new DispalyDataAdapterView(this, cursor);
listView.setAdapter(adapter);
adapter.changeCursor(cursor);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
int brandNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_PRODUCT_NAME);
int genericNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_GENERIC_NAME);
int retailPriceCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_RETAIL_PRICE);
int packSizeCol = cursor.getColumnIndex(AddNewProductEntry.COLUMN_PACK_SIZE);
int oneUnitPriceCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_ONE_UNIT_PRICE);
String brandName = cursor.getString(brandNameCol);
String genericName = cursor.getString(genericNameCol);
Double retailPrice = cursor.getDouble(retailPriceCol);
int packSize = cursor.getInt(packSizeCol);
Double oneUnitPrice = cursor.getDouble(oneUnitPriceCol);
Intent intent = new Intent(MainActivity.this,
DisplayOneProductActivity.class);
intent.putExtra("name", brandName);
intent.putExtra("genericName", genericName);
intent.putExtra("retailPrice", retailPrice);
intent.putExtra("packSize", packSize);
intent.putExtra("oneUnitPrice", oneUnitPrice);
startActivity(intent);
//finish();
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_item:
// Toast.makeText(MainActivity.this, "Item is clicked",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, AddItemActivity.class);
startActivity(intent);
return true;
case R.id.view_cart_menu:
Intent cartIntent = new Intent(this, ViewCartActivity.class);
startActivity(cartIntent);
default:
return super.onOptionsItemSelected(item);
}
}
}
and here is my AddItemActivity which is adding a new item into a database
package com.example.clnicmangmentapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
import com.example.clnicmangmentapp.data.AddNewProductDataBaseHelper;
import java.text.DecimalFormat;
public class AddItemActivity extends AppCompatActivity {
private static DecimalFormat df = new DecimalFormat("0.00");
AddNewProductDataBaseHelper mDataBaseHelper;
private Button mAddDataBtn;
private Button mCancleBtn;
private EditText mBrandName;
private EditText mGenericName;
private EditText mCompanyName;
private EditText mRetailPrice;
private EditText mPackSize;
private TextView mOneUnitPrice;
private Spinner typeSpinner;
private int mSpinnerType = AddNewProductEntry.CAP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
mDataBaseHelper = new AddNewProductDataBaseHelper(this);
mAddDataBtn = findViewById(R.id.add_data_btn);
mCancleBtn = findViewById(R.id.clear_data_btn);
mBrandName = findViewById(R.id.product_name);
mGenericName = findViewById(R.id.genric_name);
mCompanyName = findViewById(R.id.company_name);
mRetailPrice = findViewById(R.id.retail_price);
mPackSize = findViewById(R.id.pack_size);
typeSpinner = (Spinner) findViewById(R.id.medicine_type);
// for setting spinner to take the value drop down menu
setSpinner();
mAddDataBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
insertData();
clearInputs();
}
});
mCancleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddItemActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void setSpinner(){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.medicine_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
typeSpinner.setAdapter(adapter);
typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String selectedItem = (String) parent.getItemAtPosition(position);
if(!TextUtils.isEmpty(selectedItem)){
if(selectedItem.equals(getString(R.string.cap))){
Toast.makeText(AddItemActivity.this, "Cap is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.CAP;
}else if(selectedItem.equals(getString(R.string.tab))){
Toast.makeText(AddItemActivity.this, "Tab is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.TAB;
}else if(selectedItem.equals(getString(R.string.syp))){
Toast.makeText(AddItemActivity.this, "Syp is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.SYP;
}else{
Toast.makeText(AddItemActivity.this, "Inj is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.INJ;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
// this method clear all edit text after inter data to database as add button is pressed
private void clearInputs(){
mBrandName.getText().clear();
mGenericName.getText().clear();
mCompanyName.getText().clear();
mRetailPrice.getText().clear();
mPackSize.getText().clear();
}
private void insertData(){
String brand_name = mBrandName.getText().toString().toUpperCase().trim();
String generic_name = mGenericName.getText().toString().toUpperCase().trim();
String company_name = mCompanyName.getText().toString().toUpperCase().trim();
String retail_price = mRetailPrice.getText().toString().trim();
Double retailPrice = Double.parseDouble(retail_price);
String pack_size = mPackSize.getText().toString().trim();
int packSize = Integer.parseInt(pack_size);
Double oneUnitPrice = retailPrice/packSize;
// in this line of code we limiting out put to decimal places like 33.33
String convertedPrice = df.format(oneUnitPrice);
SQLiteDatabase sqLiteDatabase = mDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AddNewProductEntry.COLUMN_PRODUCT_NAME, brand_name);
contentValues.put(AddNewProductEntry.COLUMN_GENERIC_NAME, generic_name);
contentValues.put(AddNewProductEntry.COLUMN_COMPANY_NAME, company_name);
contentValues.put(AddNewProductEntry.COLUMN_RETAIL_PRICE, retail_price);
contentValues.put(AddNewProductEntry.COLUMN_PACK_SIZE, packSize);
contentValues.put(AddNewProductEntry.COLUMN_TYPE_OF_PRODUCT, mSpinnerType);
contentValues.put(AddNewProductEntry.COLUMN_ONE_UNIT_PRICE, convertedPrice);
long newRowId = sqLiteDatabase.insert(AddNewProductEntry.TABLE_NAME,null,
contentValues);
if(newRowId == -1){
Toast.makeText(AddItemActivity.this,"Error Inserting Data",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(AddItemActivity.this,"Data is Inserted Successfully",
Toast.LENGTH_LONG).show();
}
}
}
here is my DisplayDataAdapterView
package com.example.clnicmangmentapp;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
public class DispalyDataAdapterView extends CursorAdapter {
public DispalyDataAdapterView(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_view, parent,
false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView brandNameTextView = view.findViewById(R.id.brand_name_view);
TextView genericNameTextView = view.findViewById(R.id.generic_name_view);
int brandNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_PRODUCT_NAME);
int genericNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_GENERIC_NAME);
String brandName = cursor.getString(brandNameCol);
String genericName = cursor.getString(genericNameCol);
brandNameTextView.setText(brandName);
genericNameTextView.setText(genericName);
}
}
this is my Add New Prodct Contract
package com.example.clnicmangmentapp.data;
import android.provider.BaseColumns;
public class AddNewProductContract {
private AddNewProductContract(){}
public static class AddNewProductEntry implements BaseColumns{
public static final String TABLE_NAME = "add_new_product";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_PRODUCT_NAME = "product_name";
public static final String COLUMN_GENERIC_NAME = "generic_name";
public static final String COLUMN_COMPANY_NAME = "company_name";
public static final String COLUMN_RETAIL_PRICE = "retail_price";
public static final String COLUMN_PACK_SIZE = "pack_size";
public static final String COLUMN_TYPE_OF_PRODUCT = "product_type";
public static final String COLUMN_ONE_UNIT_PRICE = "one_unit_price";
public static final int CAP = 100;
public static final int TAB = 101;
public static final int SYP = 102;
public static final int INJ = 103;
}
public static class AddItemToCart implements BaseColumns{
public static final String TABLE_CART = "add_to_cart";
public static final String _CART_ID = BaseColumns._ID;
public static final String COLUMN_CART_PRODUCT_NAME = "cart_product_name";
public static final String COLUMN_CART_QUANTITY = "cart_product_quantity";
public static final String COLUMN_CART_PRICE = "cart_product_price";
public static final String COLUMN_CART_TOTAL_PRICE = "cart_total_price";
}
}
and here is my database helper class
package com.example.clnicmangmentapp.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddItemToCart;
import androidx.annotation.Nullable;
public class AddNewProductDataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "products";
private static final int DATABASE_VERSION = 1;
public AddNewProductDataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_ENTITIES = "CREATE TABLE " + AddNewProductEntry.TABLE_NAME + "("
+ AddNewProductEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ AddNewProductEntry.COLUMN_PRODUCT_NAME + " TEXT, "
+ AddNewProductEntry.COLUMN_GENERIC_NAME + " TEXT, "
+ AddNewProductEntry.COLUMN_COMPANY_NAME + " TEXT, "
+ AddNewProductEntry.COLUMN_RETAIL_PRICE + " REAL, "
+ AddNewProductEntry.COLUMN_PACK_SIZE + " INTEGER, "
+ AddNewProductEntry.COLUMN_TYPE_OF_PRODUCT + " INTEGER, "
+ AddNewProductEntry.COLUMN_ONE_UNIT_PRICE + " REAL )" ;
String CREATE_CART_TABLE = "CREATE TABLE " + AddItemToCart.TABLE_CART + "("
+ AddItemToCart._CART_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ AddItemToCart.COLUMN_CART_PRODUCT_NAME + " TEXT, "
+ AddItemToCart.COLUMN_CART_QUANTITY + " INTEGER, "
+ AddItemToCart.COLUMN_CART_PRICE + " REAL, "
+ AddItemToCart.COLUMN_CART_TOTAL_PRICE + " REAL )";
db.execSQL(CREATE_TABLE_ENTITIES);
db.execSQL(CREATE_CART_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE_PRODUCTS = " DROP TABLE IF EXISTS " +
AddNewProductEntry.TABLE_NAME;
String DROP_TABLE_ADD_TO_CART = " DROP TABLE IF EXISTS " +
AddItemToCart.TABLE_CART;
db.execSQL(DROP_TABLE_PRODUCTS);
db.execSQL(DROP_TABLE_ADD_TO_CART);
onCreate(db);
}
}
here is my list view xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Search"
android:padding="8dp"
android:layout_marginBottom="4dp">
</EditText>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
and here is my list item layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/brand_name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="#string/brand_name"
android:textSize="18sp"/>
<TextView
android:id="#+id/generic_name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Generic Name"
android:paddingLeft="8dp"/>
</LinearLayout>
please help to solve this issue
I try this code and it works now I am able to filter the list but when I click on filter result the app crashed and give me a error
android.database.StaleDataException: Attempting to access a closed
CursorWindow.Most probable cause: cursor is deactivated prior to
calling this method.
at
android.database.AbstractWindowedCursor.
checkPosition(AbstractWindowedCursor.java :141)
at
android.database.AbstractWindowedCursor.
getString(AbstractWindowedCursor.java:52)
at
com.example.clnicmangmentapp.MainActivity$3.
onItemClick(MainActivity.java:97)
here is code which I try
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
String search = constraint.toString();
String searchResult = (" SELECT * FROM " +
AddNewProductEntry.TABLE_NAME + " WHERE " +
AddNewProductEntry.COLUMN_PRODUCT_NAME + " LIKE '%" + search +
"%'");
return database.rawQuery(searchResult, null);
}
});
mSearchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
adapter.getFilter().filter(s);
// Don't forget to notify the adapter
adapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
here I work for another code this is working code
it can filter the data but data not shown only empty list but when I click on a item it shows me correct data
public void showSearch(String search){
String searchQuery = (" SELECT * FROM " +
AddNewProductEntry.TABLE_NAME + " WHERE " +
AddNewProductEntry.COLUMN_PRODUCT_NAME + " LIKE '%" + search +
"%'");
cursor = database.rawQuery(searchQuery, null);
SimpleCursorAdapter adapterSimple = new
SimpleCursorAdapter(MainActivity.this,
android.R.layout.simple_list_item_2, cursor,
new String[] {AddNewProductEntry.COLUMN_PRODUCT_NAME,
AddNewProductEntry.COLUMN_GENERIC_NAME},
new int[] {R.id.brand_name_view, R.id.generic_name_view},
0);
listView.setAdapter(adapterSimple);
adapterSimple.notifyDataSetChanged();
}
and I use this function in my mSearchEditText like this
mSearchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
String search = s.toString();
showSearch(search);
}
#Override
public void afterTextChanged(Editable s) {
}
});
this code is working and filtring the data as I type a word but it shows empty list and when I click on this list it show me the data of that list item.
As I am already displaying list of data using my DisplayDataAdpaterView so I user this method and excecated this method in my editText search's method
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String search = s.toString();
showSearch(search);
}
this method to search result from database and bind the views and show them as listview
public void showSearch(String search){
String searchQuery = (" SELECT * FROM " +
AddNewProductEntry.TABLE_NAME + " WHERE " +
AddNewProductEntry.COLUMN_PRODUCT_NAME + " LIKE '%" + search + "%'");
cursor = database.rawQuery(searchQuery, null);
// so this is the DisplayAdpater which already displaying data
// so we use this adapter to show search in a list view
adapter = new DispalyDataAdapterView(this,cursor);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

ListView duplicates items everytime I restart the activity

I feel like this is a really simple fix but I am new the android and sqlite in general. I have a array that takes data from a database and then shows them in a list. However every time I restart the app the list adds the items once again into the list. How can I make it not do this?
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.assignmenttracker.MySQLiteHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
private ListView ListView;
private Button addbutton;
public final static String ID_EXTRA="com.example.assignmenttracker._ID";
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.addbutton = (Button)this.findViewById(R.id.button1);
this.addbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this, AddAssign.class);
startActivity(intent);
}
});
}
private void populateListView() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<tasklist> contacts = db.getSometasklist();
for (tasklist cn : contacts) {
Log.d("Reading: ", "Reading all contacts..");
String log = "Id: "+cn.getID()+" ,Task: " + cn.getTask() + " ,Date: " + cn.getDate() + " ,Status: " + cn.getStatus();
Log.d("Name: ", log);
}
ListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
ListView.setAdapter(adapter);
ListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(MainActivity.this, ViewAssign.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);}
});
}
#Override
public void onResume() {
super.onResume();
populateListView();
}
}
here is the code of mysqlitehelper
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Contacts Table Columns names
private static final String TABLE_CONTACTS = "tasklist1";
private static final String KEY_ID = "id";
private static final String KEY_TASK = "task";
private static final String KEY_DESC = "desc";
private static final String KEY_MOD = "module";
private static final String KEY_DATE = "date";
private static final String KEY_TYPE = "type";
private static final String KEY_STATUS = "status";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "tasklist1";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TASKLIST_TABLE = "CREATE TABLE tasklist1 ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"task TEXT, "+
"desc TEXT, "+
"module TEXT, "+
"date TEXT, "+
"type TEXT, "+
"status INTEGER )";
db.execSQL(CREATE_TASKLIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older task list table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// create fresh task list table
this.onCreate(db);
}
public void insertTask(tasklist tasklist){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, tasklist.getTask());
values.put(KEY_DESC, tasklist.getDesc());
values.put(KEY_MOD, tasklist.getModule());
values.put(KEY_DATE, tasklist.getDate());
values.put(KEY_TYPE, tasklist.getType());
values.put(KEY_STATUS, tasklist.getStatus());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public List<tasklist> getAlltasklist(int passedid) {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +
" where id = " + passedid;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDesc(cursor.getString(2));
contact.setModule(cursor.getString(3));
contact.setDate(cursor.getString(4));
contact.setType(cursor.getString(5));
contact.setStatus(cursor.getInt(6));
String name = cursor.getString(1);
String desc =cursor.getString(2);
String module =cursor.getString(3);
String date = cursor.getString(4);
String type = cursor.getString(5);
int status = cursor.getInt(6);
ViewAssign.task= name;
ViewAssign.desc=desc;
ViewAssign.module=module;
ViewAssign.date=date;
ViewAssign.type=type;
ViewAssign.status=status;
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public List<tasklist> getSometasklist() {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDate(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public void deleteTask(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=" + row, null);
db.close();
}
}
I suspect the culprint is this:
public static ArrayList<String> ArrayofName = new ArrayList<String>();
It is a static variable, meaning that in some circumstances, it will STILL have the objects you added on app first run when you run it second time.
Possible solutions:
remove "static" keyword, or
clear ArrayOfName before populating it, eg. ArrayOfName.clear()
I know I am late but maybe it will help someone else.
You need to split ArrayList into two parts
Place the following code in MainActivity
public static ArrayList<String> ArrayofName;
And place the following in onCreate() OR onResume() method
ArrayofName = new ArrayList<String>();

Trying to make a sqlite database search app

I'm new to Android and have been working on this app for a while. Pretty much I'm loading initial values into the sqlite database with 3 columns: _id, product, and ingredients. I have an EditText box for the user to search the products to see if they have a certain ingredient in it. A listview is then printed out showing the products with these ingredients. I'm having some overall trouble with this code, specifically when I run it, it shows "Could not read row 0 col 1" from logcat.
Update: Thanks to Todd I fixed my original "Could not read row 0 and col 1" problem but now when I click the search button with edit text input "Apple" (which should output one product), the app doesn't update and stays static. Any help would be appreciated!
MySQLiteHelper.java
package com.lapetit;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCT = "product";
public static final String COLUMN_INGREDIENTS = "ingredients";
private SQLiteDatabase database;
private static final String DATABASE_NAME = "products.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_PRODUCTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_PRODUCT
+ " text not null, " + COLUMN_INGREDIENTS + " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
Cursor check = database.rawQuery("select * from products",null);
//First Time we open Database, add default Values
if ( check.getCount() < 1 )
{
database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(1,'Le Mieux Retinol Serum', 'Apples,Bananas,Carrots')");
database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(2,'Le Mieux Essence Toner', 'Apricots, Beets, Cats')");
database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(3,'Le Mieux Body Wash', 'Alcohol, Marijuana, Meth')");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
}
Products.java
package com.lapetit;
public class Products {
private long id;
private String product;
private String ingredient;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getIngredients() {
return product;
}
public void setIngredients(String ingredient) {
this.ingredient = ingredient;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return product;
}
}
ProductsDataSource.java
package com.lapetit;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ProductsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PRODUCT,
MySQLiteHelper.COLUMN_INGREDIENTS};
public ProductsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public List<Products> getAllProducts() {
List<Products> products = new ArrayList<Products>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PRODUCTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Products product = cursorToProduct(cursor);
products.add(product);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return products;
}
//Search queries
public List<Products> getSearchedProducts(String search) {
List<Products> products = new ArrayList<Products>();
String[] args = new String[1];
args[0] = "%"+search+"%";
Cursor cursor = database.rawQuery("SELECT product FROM products, _id WHERE ingredients like ?", args);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Products product = cursorToProduct(cursor);
products.add(product);
cursor.moveToNext();
}
cursor.close();
return products;
}
private Products cursorToProduct(Cursor cursor) {
Products product = new Products();
product.setId(cursor.getLong(0));
product.setProduct(cursor.getString(1));
return product;
}
}
WithActivity.java
package com.lapetit;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class WithActivity extends ListActivity {
private ProductsDataSource datasource;
private ArrayAdapter adapter;
List<Products> values = new ArrayList<Products>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.with);
EditText inputSearch = (EditText) findViewById(R.id.text);
datasource = new ProductsDataSource(this);
datasource.open();
ArrayAdapter<Products> adapter = new ArrayAdapter<Products>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
public void onClick(View view) {
ArrayAdapter<Products> adapter = (ArrayAdapter<Products>) getListAdapter();
Products product = null;
switch (view.getId()) {
case R.id.search:
EditText inputSearch = (EditText) findViewById(R.id.text);
String stringinput = (String)inputSearch.getText().toString();
List<Products> values = datasource.getSearchedProducts(stringinput);
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
with.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/text"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="text" />
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:onClick="onClick"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="400dp" />
</LinearLayout>
Failed to read row 0, column 1 from a CursorWindow which has 3 rows, 1 columns.
I think your query needs to return more columns...
In getSearchedProducts() you select only the product column:
// Select a single column.
Cursor cursor = database.rawQuery("SELECT product FROM products WHERE ingredients like ?", args);
But in cursorToProduct() you read two columns (ID and Product):
product.setId(cursor.getLong(0));
product.setProduct(cursor.getString(1));
It looks like you need to add the Id to the query.
Cursor cursor = database.rawQuery("SELECT id, product FROM products WHERE ingredients like ?", args);

no such column: KEY_PUBNAME

Im making an app which stores data in an SQLite database. I want to be able to add, edit and delete data from this database. I can app to it no problem. I am currently working on trying to delete from the database but I keep getting the same error.
(1) no such column: KEY_PUBNAME
Here is my Java file:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
db.open();
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
And here is my database adapter:
package com.example.beer_budget3;
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;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not
null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
KEY_PUBNAME is clearly declared in the database adapter.
Any help would be great.
If you see your DatabaseHelper, you've defined following:
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
The keyname you've mentioned is KEY_PUBNAME. However where you've created the table, the keyname you've defined is Pub_Name. Over here:
public static final String KEY_PUBNAME = "Pub_Name";
That's why its not found. KEY_PUBNAME is the variable you've declared and not the name of the column. You may want to try to change it in db.delete statement.

Updating specific column using a spinner widget

I am trying to update current credits column of the only row in the database using a drop down spinner which gets values from an arraylist. Very unsure about how to go about doing this operation. Thank you for any help in advance.
My database code:
package com.example.parkangel;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " TEXT NOT NULL, " + KEY_CREDITS + " TEXT
NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
}
My main activity code I will be doing the operation through:
package com.example.parkangel;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class Balance extends Activity{
Button add;
TextView display;
Spinner spinner3;
String[] money = {"Select amount", "£1", "£2", "£5", "£10"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
db.close();
tv.setText(data);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
Your question is fairly compound, getting selected field from spinner, updating database... I'm not going to provide a complete answer, but this should get you started:
This is how you would get the selected field from the spinner, which you can then use to update your database. One word of warning, I believe setOnItemSelectedListener is called when it is initially set, so you may need to ignore the first call.
Spinner spinner;
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(! (view instanceof TextView)){
// view is probably a textview, but record type if not.
System.out.println("incorrect view type " + view.getClass().getSimpleName());
return;
}
EditText et = (EditText) view;
String fieldName = et.getText().toString().trim();
//Now we got selected name, send name
//to a function that updates our database.
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I didn't find the problem but I can tell you that your code is VERY INEFFICIENT. You are using String to build your result in the getData method. Each time you try to append the new data (Row) to the old one you are creating a new string to hold the new data. If you are retrieving 1000 row from the database, this means that you are creating 1000 string to build the final one. I recommend using StringBuilder instead as following:
StringBuilder strBuilder= new StringBuilder();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
strBuilder.append( c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n");
}
return str= strBuilder.toString();
Here is an example of how to insert into your DB:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PFNAME , editText1.getText().toString());
values.put(KEY_PSNAME , stringArrayList.get(position));
values.put(KEY_CARD , "12345677");
values.put(KEY_CREDITS , "55");
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection

Categories