I am creating a trivia game for a class assignment. I initially wanted to store the questions with categories in a sqlite database. I'm strating with one table, though I want to add others for category, level, and users, but first wanted to get it working with just questions. The program compiles and installs into the emulator and the first part works fine. It's not until the app goes to create the database that I get an error. The error reads:
Caused by:
android.database.sqlite.SQLiteException: near "TABLEquestion": syntax error (code 1): , while compiling: CREATE TABLEquestion(questionIDINTEGER PRIMARY KEY,questionNameTEXT,optionATEXT,optionBTEXT,optionCTEXT,answerTEXT,questionLevelIDINTEGER,categoryIDINTEGER)
at android.database.sqlite
My code for the main activity, trivia question activity, question class, DBHelper class and the xml layout for the Trivia Question activity. Please note, the error occurs when the radio button is selected for a category, which launches the Trivia Question activity. (before adding the database, the launch worked without error). Also, I know I need to create methods for Updating and Deleting records, but wanted to get the database creation working first. I've looked at this for 2 days and cannot find the issue. Any assistance would be greatly appreciated.
CLASS QUESTION:
public class Question {
private Integer questionID;
private String questionName;
private String optionA;
private String optionB;
private String optionC;
private String answer;
private Integer questionLevelID;
private Integer categoryID;
public Question(){
//// TODO: 11/5/2016
}
public Question (Integer questionID, String questionName, String optionA,
String optionB, String optionC, String answer, Integer questionLevelID,
Integer catID){
this.questionID=questionID;
this.questionName=questionName;
this.optionA=optionA;
this.optionB=optionB;
this.optionC=optionC;
this.answer=answer;
this.questionLevelID=questionLevelID;
this.categoryID = catID;
}
public void setqID(Integer questionId){
this.questionID = questionId;
}
public void setqName(String questionName){
this.questionName=questionName;
}
public void setqOptA(String optionA){
this.optionA = optionA;
}
public void setqOptB(String optionB){
this.optionB = optionB;
}
public void setqOptC(String optionC){
this.optionC=optionC;
}
public void setqAns(String answer){
this.answer = answer;
}
public void setQLevel(Integer questionLevelID){
this.questionLevelID = questionLevelID;
}
public void setqcatID(Integer categoryID){
this.categoryID= categoryID;
}
public int getqID(){
return questionID;
}
public String getqName(){
return questionName;
}
public String getqOptA(){
return optionA;
}
public String getqOptB(){
return optionB;
}
public String getqOptC(){
return optionC;
}
public String getqAns(){
return answer;
}
public Integer getqLevel(){
return questionLevelID;
}
public Integer getqCatID(){
return categoryID;
}
}
MAIN ACTIVITY:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.util.Log;
import java.util.List;
import static android.R.attr.id;
public class EduTriviaMain extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_trivia_main);
}
public String onCheckedChanged(View view) {
boolean checked = ((RadioButton) view).isChecked();
String category = "";
switch (view.getId()) {
case R.id.englishRadioButton:
if (checked) {
category = "english";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.historyRadioButton:
if (checked) {
category = "history";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.mathRadioButton:
if (checked) {
category = "math";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
default:
break;
}
return category;
}
}
DBHelper Class:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DBHandler extends SQLiteOpenHelper{
//Database Version
private static final int DATABASE_VERSION=1;
//Database Name
private static final String DATABASE_NAME ="eduTrivia";
//table names
private static final String TABLE_QUESTION="question";
//question table column names
private static final String KEY_QUESTIONID = "questionID";
private static final String KEY_QUESTION="questionName";
private static final String KEY_OPTIONA="optionA";
private static final String KEY_OPTIONB="optionB";
private static final String KEY_OPTIONC="optionC";
private static final String KEY_ANSWER="answer";
private static final String KEY_LEVEL = "questionLevelID";
private static final String KEY_CATEGORYID="categoryID";
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE"
+ TABLE_QUESTION +"("
+ KEY_QUESTIONID +"INTEGER PRIMARY KEY,"
+ KEY_QUESTION + "TEXT,"
+ KEY_OPTIONA + "TEXT,"
+ KEY_OPTIONB + "TEXT,"
+ KEY_OPTIONC + "TEXT,"
+ KEY_ANSWER + "TEXT,"
+ KEY_LEVEL + "INTEGER,"
+ KEY_CATEGORYID + "INTEGER"+")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUESTION);
addQuestions();
}
private void addQuestions(){
Question q1 = new Question(1,"How do you write this number using words? 752",
"five hudnred sixty-two","seven hundred sixty-two", "seven hundred fifty-two",
"C",1,1);
Question q2 = new Question(2,"Round 5,764,438 to the nearest hundred thousand",
"6,200,000","5,800,000","5,700,000","B",1,1);
Question q3= new Question(3,"Which equation shows the associative property of addition",
"5+4=3+6","7+(4+3)=(7+4)+3", "0+8=8","B",1,1);
Question q4 = new Question(4,"Select the adjective in this sentence: Nina is a strong worker",
"Nina","strong","worker","B",1,2);
Question q5 = new Question (5,"Select the adjective in this sentence: The twon has three banks",
"The","town","three","C",1,2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists"+TABLE_QUESTION);
onCreate(db);
}
//constructor and getInstance() method
private static DBHandler mDBHANDLER;
public static synchronized DBHandler getInstance(Context context) {
if (mDBHANDLER==null){
mDBHANDLER=new DBHandler(context.getApplicationContext());
}
return mDBHANDLER;
}
public DBHandler(Context context){
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
public void addQuestion(Question question){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUESTIONID,question.getqID());
values.put(KEY_QUESTION,question.getqName());
values.put(KEY_OPTIONA,question.getqOptA());
values.put(KEY_OPTIONB,question.getqOptB());
values.put(KEY_OPTIONC,question.getqOptC());
values.put(KEY_ANSWER,question.getqAns());
values.put(KEY_LEVEL,question.getqLevel());
values.put(KEY_CATEGORYID,question.getqCatID());
db.insert(TABLE_QUESTION,null,values);
db.close();
}
//reading records
public Question getQuestion(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTION, new String[]{
KEY_QUESTIONID, KEY_QUESTION
},KEY_QUESTIONID + "=?",
new String[]{
String.valueOf(id)},null,null,null,null);
if (cursor !=null)
cursor.moveToFirst();
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2), cursor.getString(3),
cursor.getString(4),cursor.getString(5),Integer.parseInt(cursor.getString(6)),
Integer.parseInt(cursor.getString(7)));
return question;
}
public List<Question> getAllQuestions(){
//Select all questions query
List questionList = new ArrayList<Question>();
String selectAll = "SELECT * FROM "+TABLE_QUESTION;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectAll,null);
//loop through all rows and add to the list
if (cursor.moveToFirst()){
do{
Question question = new Question ();
question.setqID(Integer.parseInt(cursor.getString(0)));
question.setqName(cursor.getString(1));
question.setqOptA(cursor.getString(2));
question.setqOptB(cursor.getString(3));
question.setqOptC(cursor.getString(4));
question.setqAns(cursor.getString(5));
//adding to list
questionList.add(question);
}while (cursor.moveToNext());
}
return questionList;
}
}
TRIVIA QUESTION ACTIVITY:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.List;
import static android.R.id.list;
public class TriviaQuestion extends AppCompatActivity {
List<Question> questionList;
int score=0;
int questionID = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda,rdb,rdc;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trivia_question);
DBHandler db = new DBHandler(this);
questionList = db.getAllQuestions();
currentQ = questionList.get(questionID);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
setQuestionView();
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getqName());
rda.setText(currentQ.getqOptA());
rdb.setText(currentQ.getqOptB());
rdc.setText(currentQ.getqOptC());
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getqAns().equals(answer.getText())) {
score++;
}
currentQ = questionList.get(questionID);
setQuestionView();
}
});
}
}
TRIVIA QUESTION LAYOUT XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_trivia_question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rasmussenandroid.sandra.edutrivia.TriviaQuestion">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
</RelativeLayout>
The error tells you what the issue is - the SQL query is not constructed properly. There should be spaces between the individual terms - for example, CREATE TABLEquestion should be CREATE TABLE question.
Try the following line for CREATE_TABLE_QUESTION :
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE "
+ TABLE_QUESTION +" ( "
+ KEY_QUESTIONID +" INTEGER PRIMARY KEY, "
+ KEY_QUESTION + " TEXT , "
+ KEY_OPTIONA + " TEXT, "
+ KEY_OPTIONB + " TEXT, "
+ KEY_OPTIONC + " TEXT, "
+ KEY_ANSWER + " TEXT, "
+ KEY_LEVEL + " INTEGER, "
+ KEY_CATEGORYID + " INTEGER "+")";
Related
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();
}
I think I have read pretty much all the answers about this topic without getting the right answer for my case.
I have a list view in one activity called Library. When I click on an item, I would like to retrieve the informations about the clicked item in another activity. I would like these information to be in different field.
You will probably understand a bit better with my code.
This is the Library activity, on which I have my listview of what I call "tags":
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
DatabaseHelper.java :
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 DatabaseHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
private static final String TAG_ID = "_id"; // a column named "_id" is required for cursor
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public DatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aTagName, String aTagId, String aTagData) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_NAME, aTagName);
contentValues.put(TAG_MID, aTagId);
contentValues.put(TAG_DATA, aTagData);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + TAG_ID + " INTEGER PRIMARY KEY, " +
TAG_NAME + " TEXT, " + TAG_MID + " TEXT, " + TAG_DATA + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
And InfoTagActivity.java , this is in this activity that I want to get the information about the clicked item :
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
With the associated activity_info_tag.xml :
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/relativeLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/relativeLayout2"
android:paddingTop="10dp">
<TextView
android:id="#+id/tagId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_above="#+id/tagDate"
android:layout_toRightOf="#+id/tagIdText"
android:layout_toEndOf="#+id/tagIdText" />
<TextView
android:id="#+id/tagDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_alignTop="#+id/tagDateText"
android:layout_toRightOf="#+id/tagDateText"
android:layout_toEndOf="#+id/tagDateText"
android:paddingLeft="5dp"
android:paddingRight="5dp"/>
<TextView
android:id="#+id/tagInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_below="#+id/tagDate"
android:layout_toRightOf="#+id/tagInfoText"
android:layout_toEndOf="#+id/tagInfoText"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
</RelativeLayout>
My problem is that by now, when I click on a tag of the list view, it always give me the information about the first tag only. I would like to get the information about the tag on which I clicked instead.
Could someone help me on that ?
Thank you a lot for your answers !
I'm a newbie in developing an android app and I am currently developing cooking application. I want to add a new recipe to my db with recipe name, ingredients, procedures, category, notes and photo. But the problem is when I add photo from camera or gallery, it stop working and I want to view the image taken to an imageview and save it to db using a save button. But please help me. I don't know what to do with my project.
MY DBAdapter
package com.elasandesu.quickeasykitchenv3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_RNAME = "rname";
public static final String KEY_RCAT = "rcat";
public static final String KEY_RING = "ring";
public static final String KEY_RSTEPS = "rsteps";
public static final String KEY_RNOTE = "rnote";
public static final String KEY_RPHOTO = "rphoto";
//public static final String KEY_RPHOTONME = "rphotornme";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_RNAME = 1;
public static final int COL_RCAT = 2;
public static final int COL_RING = 3;
public static final int COL_RSTEPS = 4;
public static final int COL_RNOTE = 5;
public static final int COL_RPHOTO = 6;
//public static final int COL_RPHOTONME =7;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_RNAME, KEY_RCAT, KEY_RING, KEY_RSTEPS, KEY_RNOTE, KEY_RPHOTO};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Quick.sqlite";
public static final String DATABASE_TABLE = "recipe";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 5;
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_RNAME + " TEXT,"
+ KEY_RCAT + " TEXT," + KEY_RING+ " TEXT," + KEY_RSTEPS + " TEXT,"
+ KEY_RNOTE + " TEXT," + KEY_RPHOTO + " BLOB" + ")";
db.execSQL(CREATE_RECIPE_TABLE);
}
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 the database.
public long insertRow(String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_RNAME, rName);
initialValues.put(KEY_RCAT, rCat);
initialValues.put(KEY_RING, rIng);
initialValues.put(KEY_RSTEPS, rSteps);
initialValues.put(KEY_RNOTE, rNote);
//initialValues.put(KEY_RPHOTO, rPhoto);
//initialValues.put(KEY_RPHOTONME, rPhotonme);
// Insert it 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 specific row by category
public Cursor getCateg (String categ) throws SQLException {
String where = "SELECT * FROM recipe where rcat=\""+categ+"\"";
Cursor c = db.rawQuery(where, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//KEY_RCAT + " = \'" + categ + " \'";
//"select * from contacts where id="+id+"", null
// 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 rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_RNAME, rName);
newValues.put(KEY_RCAT, rCat);
newValues.put(KEY_RING, rIng);
newValues.put(KEY_RSTEPS, rSteps);
newValues.put(KEY_RNOTE, rNote);
//newValues.put(KEY_RPHOTO, rPhoto);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteAssetHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
Activity Code
package com.elasandesu.quickeasykitchenv3;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Addrecipe extends Activity implements OnItemSelectedListener{
String[] cat = {"BEEF","CHICKEN",
"PORK", "FISH", "VEGETABLES"};
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
private String selectedImagePath;
String DB_NAME = Environment.getExternalStorageDirectory() + "/Quick.sqlite";
String TABLE_NAME = "recipe";
ImageView recphoto;
DBAdapter db;
EditText recname, recing, recsteps, recnote;
Spinner spinner1;
TextView category;
Button save, reset, upload;
public static String rcat = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrecipe);
category = (TextView) findViewById(R.id.categorytxtview);
spinner1 = (Spinner) findViewById(R.id.categorysp);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cat);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter_state);
spinner1.setOnItemSelectedListener(this);
save = (Button) findViewById(R.id.savebtn);
reset = (Button) findViewById(R.id.resetbtn);
recname = (EditText) findViewById(R.id.recipename);
recing = (EditText) findViewById(R.id.ingredient);
recnote = (EditText) findViewById(R.id.note);
recsteps = (EditText) findViewById(R.id.procedure);
recphoto= (ImageView) findViewById(R.id.image);
openDB();
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
Button addImage = (Button) findViewById(R.id.uploadbtn);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
//insert activity here :D
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras= data.getExtras();
if (extras != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage.compress(CompressFormat.PNG, 0, stream);
byte[] bytes = stream.toByteArray();
recphoto.setImageBitmap(selectedImage);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
recphoto.setImageURI(selectedImageUri);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("crop", "true");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
db = new DBAdapter(this);
db.open();
}
private void closeDB() {
db.close();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void saveHasBeenClicked (View v) {
String rName = recname.getText().toString();
String rIng = recing.getText().toString();
String rSteps =recsteps.getText().toString();
String rNote = recnote.getText().toString();
String rCat = (String) spinner1.getSelectedItem();
long newId = db.insertRow(rName,"\n"+ rCat," \n "+ rIng," \n" + rSteps, rNote);
Cursor cursor = db.getRow(newId);
displayRecordSet(cursor);
Intent evilIntent = new Intent(Addrecipe.this, Selected.class);
startActivity(evilIntent);
}
public void onClick_ClearAll(View v) {
db.deleteAll();
Toast.makeText(getBaseContext(), "Cleared ", Toast.LENGTH_LONG).show();
}
// Display an entire record set to the screen.
private void displayRecordSet(Cursor cursor) {
String message = "";
// populate the message from the cursor
// Reset cursor to start, checking to see if there's data:
if (cursor.moveToFirst()) {
do {
// Process the data:
int id = cursor.getInt(DBAdapter.COL_ROWID);
String rName = cursor.getString(DBAdapter.COL_RNAME);
String rCat = cursor.getString(DBAdapter.COL_RCAT);
String rIng = cursor.getString(DBAdapter.COL_RING);
String rSteps = cursor.getString(DBAdapter.COL_RSTEPS);
String rNote = cursor.getString(DBAdapter.COL_RNOTE);
// Append data to the message:
message += "id=" + id
+", Recipe Name : " + rName
+", Category : " + rCat
+", Ingredients : " + rIng
+", Procedure: " + rSteps
+", Note: " + rNote
+"\n";
} while(cursor.moveToNext());
Toast.makeText(getBaseContext(), "Save Has Been Clicked "+ message, Toast.LENGTH_LONG).show();
}
// Close the cursor to avoid a resource leak.
cursor.close();
}
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/clr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/nb"
android:onClick="displayClicked"
android:screenOrientation="landscape"
tools:ignore="HardcodedText" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1462dp" >
<EditText
android:id="#+id/recipename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/recipenametxtview"
android:layout_alignBottom="#+id/recipenametxtview"
android:layout_alignParentRight="true"
android:layout_marginRight="70dp"
android:ems="10"
android:hint="Type the Recipe Name"
tools:ignore="TextFields" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/categorytxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recipenametxtview"
android:layout_below="#+id/recipename"
android:layout_marginTop="50dp"
android:text="Category:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ingtxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/categorytxtview"
android:layout_below="#+id/categorysp"
android:layout_marginTop="42dp"
android:text="Ingredients:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categorysp"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignLeft="#+id/recipename"
android:layout_alignRight="#+id/recipename"
android:layout_alignTop="#+id/categorytxtview" />
<TextView
android:id="#+id/notetxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="253dp"
android:text="Note:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/ingredient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingtxtview"
android:layout_alignRight="#+id/categorysp"
android:layout_below="#+id/ingtxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type Here the Ingredients : e.g. 1 kilo of Flour"
android:inputType="text"
android:singleLine="false"
tools:ignore="TextFields" />
<EditText
android:id="#+id/procedure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_alignRight="#+id/ingredient"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type in this format 1.) procedure 1 [newline] 2.) procedure 2"
tools:ignore="TextFields" />
<EditText
android:id="#+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/notetxtview"
android:layout_alignRight="#+id/procedure"
android:layout_below="#+id/notetxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Includes information, cautions and other health information"
tools:ignore="TextFields" />
<TextView
android:id="#+id/recipenametxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/itemRname"
android:layout_marginLeft="62dp"
android:layout_marginTop="67dp"
android:text="Recipe Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phototxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/note"
android:layout_below="#+id/note"
android:layout_marginTop="101dp"
android:text="Photo:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/proceduretxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingredient"
android:layout_below="#+id/ingredient"
android:layout_marginTop="172dp"
android:text="Procedure:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/uploadbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/phototxtview"
android:layout_alignBottom="#+id/phototxtview"
android:layout_toRightOf="#+id/ingtxtview"
android:text="Upload Photo" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_below="#+id/uploadbtn"
android:layout_marginTop="42dp"/>
<Button
android:id="#+id/resetbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/savebtn"
android:layout_alignBottom="#+id/savebtn"
android:layout_alignRight="#+id/note"
android:layout_marginRight="55dp"
android:onClick="onClick_ClearAll()"
android:text="Reset" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/uploadbtn"
android:layout_below="#+id/image"
android:layout_marginTop="56dp"
android:onClick="saveHasBeenClicked"
android:text="Save" />
</RelativeLayout>
</ScrollView>
please help me.. it will be a great help.
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);
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.