Creating and Updating only a single value in Sqlite - java

I want to create a new table in my Database (meaning I will have two tables). In that table I will only have one and only value and the use of that only value is I will get it and I will perform addition or subtraction and inserting/updating it again for the new value that has been subtracted or added values (basically it is an integer value or boolean for decimals). I'm still new at sqlite and a beginner at android development.
My Question is that how will I have/insert only one value in the table BY DEFAULT and how will I get and update it. Because when I add INSERT query in the activity itself or in the button/fab it will add new values each time I will open the fragment itself or press the button/fab. How will I have only one data in there BY DEFAULT and how to get it so I can add or subtract values in to it and update it for the new value?
I created two tables:
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_CASHFLOW_TABLE = "CREATE TABLE " + ItemEntry.TABLE_NAME2 + " (" +
ItemEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ItemEntry.COLUMN_INCOME + " INTEGER NOT NULL, " +
ItemEntry.COLUMN_SAVINGS + " INTEGER NOT NULL " +
");";
final String SQL_CREATE_ITEMLIST_TABLE = "CREATE TABLE " + ItemEntry.TABLE_NAME + " (" +
ItemEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ItemEntry.COLUMN_LABEL + " TEXT NOT NULL, " +
ItemEntry.COLUMN_DETAIL + " TEXT, " +
ItemEntry.COLUMN_AMOUNT + " INTEGER NOT NULL, " +
ItemEntry.COLUMN_DATE + " TEXT " +
");";
db.execSQL(SQL_CREATE_ITEMLIST_TABLE);
db.execSQL(SQL_CREATE_CASHFLOW_TABLE);
}
Codes I tried from bk7:
public void insertOrUpdateTheIncomeAndSavings(int income, int savings){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * from "+ItemEntry.TABLE_NAME2,null);
if(cursor.moveToNext()){
//update the values of first row here
//update income
Cursor cursor2 = sqLiteDatabase.rawQuery("UPDATE "+ItemEntry.TABLE_NAME2+" SET "+ItemEntry.COLUMN_INCOME+
" = "+ income + " WHERE "+ItemEntry._ID +" = 1",null);
}else{
//insert the value here
ContentValues cv = new ContentValues();
cv.put(ItemEntry.COLUMN_INCOME, 0);
cv.put(ItemEntry.COLUMN_SAVINGS, 0);
}
if(cursor!=null){
cursor.close();
}
sqLiteDatabase.close();
}
How can I do it in income java:
package com.example.admin.test2;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class Income extends Fragment {
public Income() {
// Required empty public constructor
}
private EditText textInput;
private FloatingActionButton fabPlus;
private FloatingActionButton fabMinus;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate (R.layout.fragment_income, container, false);
textInput = (EditText) view.findViewById(R.id.editText2);
fabPlus = (FloatingActionButton) view.findViewById(R.id.fabPlus);
fabMinus = (FloatingActionButton) view.findViewById(R.id.fabMinus);
fabPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
}
and get values from this editText:
textInput = (EditText) view.findViewById(R.id.editText2);
I want to display the input I inputted in the database in this textView but it does not work.. please check the code:
public void getIncome() {
Cursor cur = mDatabase.rawQuery("SELECT " + ItemContract.ItemEntry.COLUMN_INCOME + " as Income FROM " + ItemContract.ItemEntry.TABLE_NAME2
, null);
if (cur.moveToFirst()) {
int incomeTotal = cur.getInt(cur.getColumnIndex("Income"));// get final total
income.setText("₱ " + incomeTotal);
}

Here were inserting first row if it does not exist and updating the first row is exists.
public void insertOrUpdateTheIncomeAndSavings(int income, int savings){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from "+ItemEntry.TABLE_NAME2,null);
if(cursor.moveToNext()){
//update the values of first row here
}else{
//insert the value here
}
if(cursor!=null){
cursor.close();
}
sqLiteDatabase.close();
}
Edit: Add this in Onclick
DBHelper dbhelper = new DBHelper(getActivity());
int income = Integer.valueOf(incomeEditText.getText().toString());
int savings = Integer.valueOf(savingsEditText.getText().toString());
dbhelper.insertOrUpdateTheIncomeAndSavings(income,savings);

public void updateEmployeeName(String empNo,String new_empname) {
Cursor cursor = null;
String empName = "";
try {
cursor = SQLiteDatabaseInstance_.rawQuery("SELECT EmployeeName
FROM Employee WHERE EmpNo=?", new String[] {empNo + ""});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
empName = cursor.getString(cursor.getColumnIndex("EmployeeName"));
update(empname);
}else{
update(new_empname);
}
}finally {
cursor.close();
}
}
**Update single value use this query:-**
public void update(){
ContentValues cv = new ContentValues();
cv.put(ColumnName, newValue);
db.update(TABLE_NAME, cv, Column + "= ?", new String[] {rowId});
}
**delete single value use this query:-**
public void delete_singlevalue(String newValue) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("delete from TABLE_NAME where
ColumnName="+"'"+newValue+"'");
db.close();
}

Related

I can't see the first item added to my ListView

I have a database made with OpenSQLiteHelper which where I am getting a String of names from and adding it to a ListView. I can never see the first item in the database and the ListView only starts from the second item in the Database.
I am getting Strings from COL_2 (names) in my database.
ListView Class
public class Castawaylist extends AppCompatActivity {
private static final String TAG = "CastList";
myDbAdapter mydb;
private ListView castview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_castawaylist);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
castview = (ListView) findViewById(R.id.listView);
mydb = new myDbAdapter(this);
populateCastList();
}
String score;
private void populateCastList()
{
//get the data and append to the list
Log.d(TAG, "populateCastList: Displaying List of Castaways.");
Cursor data = mydb.getData();
//int save = data.getInt(2);
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext())
{
listData.add(data.getString(1) +
" " + data.getInt(2)); //get value from database at column 1, then add it to array list
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData); //Creates the list adapter and set it
castview.setAdapter(adapter);
castview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String nametest = "";
int u = 0;
while(!adapterView.getItemAtPosition(i).toString().substring(u,u+1).equals(" "))
{
nametest = nametest + adapterView.getItemAtPosition(i).toString().substring(u, u+1);
u = u + 1;
}
Log.d(TAG, "onItemClick: You Clicked on " + nametest);
Cursor data = mydb.getItemID(nametest); //Get the ID associated with that name
int itemID = -1;
while(data.moveToNext())
{
itemID = data.getInt(0);
}
if(itemID > -1)
{
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editCastaway = new Intent(Castawaylist.this, EditCastaway.class);
editCastaway.putExtra("id", itemID);
editCastaway.putExtra("name", nametest);
//editCastaway.putExtra("score", data.getInt(2));
startActivity(editCastaway);
}else
{
toastText("No ID associated with that name");
}
}
});
}
private void toastText(String text)
{
Toast.makeText(this,text, Toast.LENGTH_SHORT).show();
}}
ListView XML Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
Database Helper Class
public class myDbAdapter extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "Castaways.db";
public static final String TABLE_NAME = "Survivor_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "MARK";
public myDbAdapter(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MARK INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean addData(String name,int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,score);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL_1 + " FROM " + TABLE_NAME +
" WHERE " + COL_2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
public boolean updateData(String id,String name,String surname,int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,score);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_2 +
" = '" + newName + "' WHERE " + COL_1 + " = '" + id + "'" +
" AND " + COL_2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL_1 + " = '" + id + "'" +
" AND " + COL_2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public void updateScore(int newScore, int id, int oldScore){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_3 +
" = '" + newScore + "' WHERE " + COL_1 + " = '" + id + "'" +
" AND " + COL_3 + " = '" + oldScore + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newScore);
db.execSQL(query);
}
public void clearData()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
db.close();
}}
Thanks for the help!
Not sure but it seems that the problem is here:
while(data.moveToNext())
It could be that moveToNext() is triggered on the move to the next item after leaving the previous one in other words it will be triggered for the first time after leaving item #1 behind)
Try using indexed loop instead.i.e. for (int i=0; ....
In this code:
while(data.moveToNext())
{
itemID = data.getInt(0);
}
It will trigger the moveToNext() function and then do the while. So you could solve it using a do while instead
do{
itemID = data.getInt(0);
}while(data.moveToNext())
In my research of using Cursor your initial setup is correct
while(data.moveToNext())...
Cursor starts before the rows and the initial call moveToNext() moves it to the first row.
One glaring issue is that you are not closing the Cursor.
while(data.moveToNext())
{
listData.add(data.getString(1) +
" " + data.getInt(2)); //get value from database at column 1, then add it to array list
}
// Close the Cursor here and again after the second one you create
data.close();
The second thing I see being a potential issue is that you are not accessing the correct value in the onClick
// int i might not be 0 at some point
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
i--;// maybe try subtracting 1 from i. Alternative is to do that when i is being used
String nametest = "";
int u = 0;
// or subtract here
while(!adapterView.getItemAtPosition(i-1).toString().substring(u,u+1).equals(" "))
{
nametest = nametest + adapterView.getItemAtPosition(i-1).toString().substring(u, u+1);
u = u + 1;
}

How to retrieve data from sqlite from list view click and view on a different activity android studio

I am a newbie in the android studio and I am trying to make an attendance mobile app where:
- I can add students and view the list of students added
- Add events and view the list of events added
- Add attendance where I have a spinner, auto-complete text view, and a button. on the spinner, the event name is retrieving from the SQLite database table. and on the autocomplete text view, last names of the students is retrieving also from the table in SQLite DB.
My problem is I cant don't know how to view the list of students who are present at that event. I would want it to do when I click on the events listview, new activity will open and shows all the students who are present.
My student's table has StudentID (primary key, autoincrement), last name, first name, year.
Events table has EventId (primary key, autoincrement), event name, date, time.
Attendance Table : attendanceID(primary key, autoincrement),eventname, student last name.
I would really appreciate your help guys. here's my code.
ViewEvents.java
package com.example.acer.finals;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ViewEvents extends AppCompatActivity{
DatabaseHelper myDB;
private ListView mylistView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewevents);
mylistView = (ListView) findViewById(R.id.listView3);
myDB = new DatabaseHelper(this);
populateEventView();
}
private void populateEventView()
{
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getEventsList();
int numRows = data.getCount();
if(numRows == 0)
{
Toast.makeText(ViewEvents.this, "Event List Empty!", Toast.LENGTH_LONG).show();
}
else {
while (data.moveToNext()) {
theList.add("Event Name: " + data.getString(1) + "\nDate: " + data.getString(2) + "\nTime: " + data.getString(3));
}
}
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
mylistView.setAdapter(listAdapter);
//set an onItemClickListener to the ListView
mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String ename = adapterView.getItemAtPosition(i).toString();
Cursor data = myDB.getEventName(ename);
Intent intent = new Intent(ViewEvents.this, Load_Attendance.class);
startActivity(intent);
}
});
}
}
AddAttendance.java
package com.example.acer.finals;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class AddAttendance extends AppCompatActivity {
Spinner spnrEvent;
Button btnSave;
AutoCompleteTextView autoCtv;
DatabaseHelper myDB;
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> all_Lname = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayAdapter<String> AllNames_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
spnrEvent = (Spinner) findViewById(R.id.spnrEvent);
btnSave = (Button) findViewById(R.id.btnSave);
autoCtv = (AutoCompleteTextView) findViewById(R.id.autoCtv);
//ADAPTER
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
myDB = new DatabaseHelper(this);
final Cursor event = myDB.getAllEvents();
while(event.moveToNext())
{
String name = event.getString(1);
names.add(name);
}
spnrEvent.setAdapter(adapter);
//================================================
all_Lname = myDB.getAll_Lname();
AllNames_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, all_Lname);
autoCtv.setAdapter(AllNames_adapter);
//================================================
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String evname = spnrEvent.getSelectedItem().toString();
String lastname = autoCtv.getText().toString();
if(evname.length() != 0 && lastname.length() != 0){
createAttendance(evname,lastname);
spnrEvent.setSelection(0);
autoCtv.setText("");
}else{
Toast.makeText(AddAttendance.this,"You must put something in the text field!",Toast.LENGTH_LONG).show();
}
}
});
}
public void createAttendance(String evname, String lastname){
boolean insertData = myDB.createAttendanceTB(evname,lastname);
if(insertData==true){
Toast.makeText(AddAttendance.this,"Successfully Entered Data!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(AddAttendance.this,"Something went wrong :(.",Toast.LENGTH_LONG).show();
}
}
}
Load_Attendance.java
package com.example.acer.finals;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Load_Attendance extends AppCompatActivity {
DatabaseHelper myDB;
private ListView attendance_list;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadattendance);
attendance_list = (ListView) findViewById(R.id.attendance_list);
myDB = new DatabaseHelper(this);
populateListViewAttendance();
}
private void populateListViewAttendance()
{
String name= "";
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getEventAttendance(name);
int numRows = data.getCount();
if(numRows == 0)
{
Toast.makeText(Load_Attendance.this, "Attendance List Empty!", Toast.LENGTH_LONG).show();
}
else {
while(data.moveToNext())
{
theList.add(data.getString(1));
}
}
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
attendance_list.setAdapter(listAdapter);
}
}
DatabaseHelper.java
package com.example.acer.finals;
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;
/**
* Created by acer on 12/3/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Finals";
// Table Names
private static final String StudentInfo = "StudentInfo";
private static final String EventTB= "EventTB";
private static final String AttendanceTB = "AttendanceTB";
// StudentInfo Table - column names
private static final String StudentID = "StudentID";
private static final String LastName = "LastName";
private static final String FirstName = "FirstName";
private static final String Year = "Year";
// TAGS Table - column names
private static final String EventID = "EventID";
private static final String EventName = "EventName";
private static final String EDate = "EDate";
private static final String Time = "Time";
// NOTE_TAGS Table - column names
private static final String AttendanceID = "AttendanceID";
private static final String Event_Name = "EventName";
private static final String Student_Lname = "Student_Lname";
public DatabaseHelper(Context context){
super(context,DATABASE_NAME, null, DATABASE_VERSION);
}
// Table Create Statements
// createStudentInfo table create statement
private static final String createStudentInfo = "CREATE TABLE " + StudentInfo + "("
+ StudentID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ LastName + " TEXT,"
+ FirstName + " TEXT,"
+ Year + " TEXT " + ")";
// createEventTB table create statement
private static final String createEventTB = "CREATE TABLE " + EventTB + "("
+ EventID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ EventName + " TEXT,"
+ EDate + " TEXT,"
+ Time + " TEXT " + ")";
// AttendanceTB table create statement
private static final String createAttendanceTB = "CREATE TABLE " + AttendanceTB + "("
+ AttendanceID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Event_Name + " TEXT,"
+ Student_Lname + " TEXT "+ ")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createStudentInfo);
db.execSQL(createEventTB);
db.execSQL(createAttendanceTB);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + createStudentInfo);
db.execSQL("DROP TABLE IF EXISTS " + createEventTB);
db.execSQL("DROP TABLE IF EXISTS " + createAttendanceTB);
// create new tables
onCreate(db);
}
public boolean createStudentInfo(String lname, String fname, String year)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LastName,lname);
contentValues.put(FirstName,fname);
contentValues.put(Year, year);
long result = db.insert(StudentInfo, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
public boolean createEventTB(String ename, String edate, String time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EventName,ename);
contentValues.put(EDate,edate);
contentValues.put(Time,time);
long result = db.insert(EventTB, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
public boolean createAttendanceTB(String evname, String lastname)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Event_Name,evname);
contentValues.put(Student_Lname,lastname);
long result = db.insert(AttendanceTB, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
//returns all data from StudentInfo db
public Cursor getStudentsList() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
return data;
}
//returns all events list
public Cursor getEventsList() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + EventTB;
Cursor data = db.rawQuery(query, null);
return data;
}
//Returns only the ID that matches the name passed in
public Cursor getEventName(String ename){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + ename + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//Returns only the ID that matches the name passed in
public Cursor getEventAttendance(String name){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * " + Student_Lname + " FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//GET ALL Events
public Cursor getAllEvents()
{
SQLiteDatabase db = this.getWritableDatabase();
String[] columns={EventID,EventName};
return db.query(EventTB, columns, null, null, null, null, null);
}
//spinner
public ArrayList<String> getAll_Lname()
{
ArrayList<String> all_Lname = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT DISTINCT " + LastName + " FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
if (data.getCount() > 0)
{
data.moveToFirst();
}
while(!data.isAfterLast())
{
all_Lname.add(data.getString(0));
data.moveToNext();
}
return all_Lname;
}
}
activity_viewevents.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/listView3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="20dp" />
</RelativeLayout>
acivity_addattendance.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Choose Event :"
android:id="#+id/textView15"
android:textSize="22sp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spnrEvent"
android:layout_gravity="right"
android:clickable="false"
android:layout_below="#+id/textView15"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SAVE"
android:id="#+id/btnSave"
android:textSize="25sp"
android:layout_marginTop="45dp"
android:layout_below="#+id/autoCtv"
android:layout_alignLeft="#+id/autoCtv"
android:layout_alignStart="#+id/autoCtv"
android:layout_alignRight="#+id/autoCtv"
android:layout_alignEnd="#+id/autoCtv"
android:background="#color/material_deep_teal_500"
android:textColor="#color/primary_text_default_material_dark" />
<AutoCompleteTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/autoCtv"
android:layout_marginTop="50dp"
android:textSize="20sp"
android:visibility="visible"
android:layout_below="#+id/spnrEvent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Last Name"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</RelativeLayout>
activity_loadattendance.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/attendance_list" />
</LinearLayout>
When you click on an event you extract the event name of the clicked event. You then want to start an activity but passing the event name to that activity.
You can do this by adding an Intent Extra e.g. :-
Intent intent = new Intent(ViewEvents.this, Load_Attendance.class);
intent.putExtra("EVENT_NAME",ename); //<<<<<<<< ADD this Line
startActivity(intent);
Then Load_Attendance could be :-
public class Load_Attendance extends AppCompatActivity {
DatabaseHelper myDB;
private ListView attendance_list;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadattendance);
attendance_list = (ListView) findViewById(R.id.attendance_list);
myDB = new DatabaseHelper(this);
populateListViewAttendance(getIntent().getStringExtra("EVENT_NAME")); //<<<<<<<< invoke with retrieved event name
}
private void populateListViewAttendance(String name) //<<<<<<<< added parameter
{
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getEventAttendance(name);
int numRows = data.getCount();
if(numRows == 0)
{
Toast.makeText(Load_Attendance.this, "Attendance List Empty!", Toast.LENGTH_LONG).show();
}
else {
while(data.moveToNext())
{
theList.add(data.getString(1));
}
}
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
attendance_list.setAdapter(listAdapter);
}
}
//<<<<<<<< indicates changed/added lines of code
Note this hasn't been tested and assumes that the existing code was working, there might be the odd error.
P.S. you should be closing Cursors when finished with them.
Edits after comments due to chain of failures.
The following is code based upon your code but simplified to the basics of what you want in regard to this question.
That is a List of events is presented in a Listview, clicking on an Item produces a list of the attendees.
However, this is all done within the same activity, the attendees on the clicked event are list in the log. In short this verifies that the basic process provided in the above answer works and rather the issues that you are having are very likely due to the data that you have in the database.
The Code
activity_main.xml :-
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="acer.com.finals.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<ListView
android:id="#+id/EventsList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Finals";
// Table Names
private static final String StudentInfo = "StudentInfo";
private static final String EventTB= "EventTB";
private static final String AttendanceTB = "AttendanceTB";
// StudentInfo Table - column names
private static final String StudentID = "StudentID";
private static final String LastName = "LastName";
private static final String FirstName = "FirstName";
private static final String Year = "Year";
// TAGS Table - column names
private static final String EventID = "EventID";
private static final String EventName = "EventName";
private static final String EDate = "EDate";
private static final String Time = "Time";
// NOTE_TAGS Table - column names
private static final String AttendanceID = "AttendanceID";
private static final String Event_Name = "EventName";
private static final String Student_Lname = "Student_Lname";
public DatabaseHelper(Context context){
super(context,DATABASE_NAME, null, DATABASE_VERSION);
}
// Table Create Statements
// createStudentInfo table create statement
private static final String createStudentInfo = "CREATE TABLE " + StudentInfo + "("
+ StudentID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ LastName + " TEXT,"
+ FirstName + " TEXT,"
+ Year + " TEXT " + ")";
// createEventTB table create statement
private static final String createEventTB = "CREATE TABLE " + EventTB + "("
+ EventID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ EventName + " TEXT,"
+ EDate + " TEXT,"
+ Time + " TEXT " + ")";
// AttendanceTB table create statement
private static final String createAttendanceTB = "CREATE TABLE " + AttendanceTB + "("
+ AttendanceID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Event_Name + " TEXT,"
+ Student_Lname + " TEXT "+ ")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createStudentInfo);
db.execSQL(createEventTB);
db.execSQL(createAttendanceTB);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + StudentInfo);
db.execSQL("DROP TABLE IF EXISTS " + EventTB);
db.execSQL("DROP TABLE IF EXISTS " + AttendanceTB);
// create new tables
onCreate(db);
}
public boolean createStudentInfo(String lname, String fname, String year)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LastName,lname);
contentValues.put(FirstName,fname);
contentValues.put(Year, year);
long result = db.insert(StudentInfo, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
public boolean createEventTB(String ename, String edate, String time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EventName,ename);
contentValues.put(EDate,edate);
contentValues.put(Time,time);
long result = db.insert(EventTB, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
public boolean createAttendanceTB(String evname, String lastname)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Event_Name,evname);
contentValues.put(Student_Lname,lastname);
long result = db.insert(AttendanceTB, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
//returns all data from StudentInfo db
public Cursor getStudentsList() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
return data;
}
//returns all events list
public Cursor getEventsList() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + EventTB;
Cursor data = db.rawQuery(query, null);
return data;
}
//Returns only the ID that matches the name passed in
public Cursor getEventName(String ename){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + ename + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//Returns only the ID that matches the name passed in
public Cursor getEventAttendance(String name){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//GET ALL Events
public Cursor getAllEvents()
{
SQLiteDatabase db = this.getWritableDatabase();
String[] columns={EventID,EventName};
return db.query(EventTB, columns, null, null, null, null, null);
}
//spinner
public ArrayList<String> getAll_Lname()
{
ArrayList<String> all_Lname = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT DISTINCT " + LastName + " FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
if (data.getCount() > 0)
{
data.moveToFirst();
}
while(!data.isAfterLast())
{
all_Lname.add(data.getString(0));
data.moveToNext();
}
return all_Lname;
}
}
Note that although this is similar there are a 2) important changes :-
1 the onUpgrade method rather than concatenating the table create SQL instead just concatenates the respective table name. The original onUpgrade method would fail.
2 As per the answer and comments the getEventAttendance method has been amended to take the eventname as a parameter and to select all columns from the attendance table.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbhelper;
ListAdapter mEventListAdapter;
ArrayList<String> mEventList;
ListView mEventsListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEventsListView = this.findViewById(R.id.EventsList);
dbhelper = new DatabaseHelper(this);
dbhelper.getWritableDatabase().delete("EventTB",null,null);
dbhelper.getWritableDatabase().delete("StudentInfo", null,null);
dbhelper.getWritableDatabase().delete("AttendanceTB", null,null);
dbhelper.createEventTB("The Main Event","31/12/2017","10:30");
dbhelper.createEventTB("The Normal Event","31/12/2017","10:30");
dbhelper.createEventTB("The Minor Event","31/12/2017","10:30");
dbhelper.createStudentInfo("Bloggs","Fred","2017");
dbhelper.createStudentInfo("Smith","Tom", "2016");
dbhelper.createStudentInfo("Thomas","John","2015");
dbhelper.createAttendanceTB("The Main Event","Bloggs");
dbhelper.createAttendanceTB("The Main Event", "Smith");
dbhelper.createAttendanceTB("The Normal Event","Thomas");
dbhelper.createAttendanceTB("The Minor Event","Thomas");
dbhelper.createAttendanceTB("The Minor Event","Smith");
Cursor csr = dbhelper.getEventsList();
mEventList = new ArrayList<>();
while (csr.moveToNext()) {
mEventList.add(csr.getString(1));
}
mEventListAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,mEventList);
mEventsListView.setAdapter(mEventListAdapter);
mEventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String eventname = parent.getItemAtPosition(position).toString();
Log.d("EVLIST_ITEMCLCK","You clicked Item at Position " + position + " and extracted Event name as " + eventname);
logEventAttendance(eventname);
}
});
}
private void logEventAttendance(String eventname) {
Cursor csr = dbhelper.getEventAttendance(eventname);
Log.d("EVATTEND","Number of attendance rows extracted is " + csr.getCount());
while (csr.moveToNext()) {
Log.d("EVATTEND", "Attendee is " + csr.getString(2) + " at Event " + csr.getString(1));
}
}
}
This :-
1) does a very usual initialisation and then gets the ListView by it's ID.
2) Creates an instance of the database helper, empties the 3 tables (database and tables will be created for the first run of the App).
3) Add 3 Events.
4) Add 3 Students.
5) Add Attendances at Events NOTE IT IS VITAL THAT EVENT NAMES AND STUDENT LAST NAMES EXACTLY MATCH THE RESPECTIVE EVENT NAME AND STUDENT NAME
Note that using names as references is restrictive e.g. you couldn't have Student's Tom Smith and Fred Smith as you use the last name as reference.
Normally ID's are used for referencing/linking columns between tables.
6) get the EventList and convert it to an ArrayList.
7) Setup the ListAdapter to use the ArrayList of event names.
8) Tie the Adapter to the ListView
9) Add an onItemClick listener to the listview.
10) When an item is clicked the number of attendance rows for the event is displayed in the log and for each (if any) a log entry is made.
Output
The following is the output from the above after clicking each item in turn :-
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVLIST_ITEMCLCK: You clicked Item at Position 0 and extracted Event name as The Main Event
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVATTEND: Number of attendance rows extracted is 2
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVATTEND: Attendee is Bloggs at Event The Main Event
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVATTEND: Attendee is Smith at Event The Main Event
12-12 04:58:54.192 2860-2860/acer.com.finals D/EVLIST_ITEMCLCK: You clicked Item at Position 1 and extracted Event name as The Normal Event
12-12 04:58:54.193 2860-2860/acer.com.finals D/EVATTEND: Number of attendance rows extracted is 1
12-12 04:58:54.193 2860-2860/acer.com.finals D/EVATTEND: Attendee is Thomas at Event The Normal Event
12-12 04:58:55.477 2860-2860/acer.com.finals D/EVLIST_ITEMCLCK: You clicked Item at Position 2 and extracted Event name as The Minor Event
12-12 04:58:55.478 2860-2860/acer.com.finals D/EVATTEND: Number of attendance rows extracted is 2
12-12 04:58:55.478 2860-2860/acer.com.finals D/EVATTEND: Attendee is Thomas at Event The Minor Event
12-12 04:58:55.478 2860-2860/acer.com.finals D/EVATTEND: Attendee is Smith at Event The Minor Event
Note this is intended to supplement the answer.

Data not being stored in SQLite database for some reason? Errors

i'm trying to store some data within a new my sql database and am getting logcat errors saying the table does not exist despite me creating a method to do this. Here is my code!
DataBaseHelper2.java -
package com.example.david.myview3;
/**
* Created by David on 23/03/2017.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper2 extends SQLiteOpenHelper {
public DataBaseHelper2(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE1);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE2);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE3);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE4);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE5);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion + " to " + _newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
SurveyDataBaseAdapter -
package com.example.david.myview3;
/**
* Created by David on 23/03/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class SurveyDataBaseAdapter {
static final String DATABASE_NAME = "survey.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE1 = "create table " + "USER" +
"( " + "ID" + " integer primary key autoincrement," + "ID int,NAME text); ";
static final String DATABASE_CREATE2 = "create table " + "QUESTION" +
"( " + "ID2" + " integer primary key autoincrement," + "QUESTION text,ANSWER1 text, ANSWER2 text, ANSWER3 text); ";
static final String DATABASE_CREATE3 = "create table " + "RESPONSE" +
"( " + "ID3" + " integer primary key autoincrement," + "ID int,QUESTION text, ANSWER int); ";
// Variable to hold the database instance
public SQLiteDatabase db2;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper2 dbHelper2;
public SurveyDataBaseAdapter(Context _context) {
context = _context;
dbHelper2= new DataBaseHelper2(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public SurveyDataBaseAdapter open() throws SQLException {
db2 = dbHelper2.getWritableDatabase();
return this;
}
public void close() {
db2.close();
}
public SQLiteDatabase getDatabaseInstance() {
return db2;
}
public void insertQuestion(String question, String answerOne, String answerTwo, String answerThree) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("QUESTION", question);
newValues.put("ANSWER1", answerOne);
newValues.put("ANSWER2", answerTwo);
newValues.put("ANSWER3", answerThree);
// Insert the row into your table
db2.insert("QUESTION", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
//new try
public void insertEntry2(String question, String answer) {
ContentValues newValues2 = new ContentValues();
// Assign values for each row.
newValues2.put("QUESTION", question);
newValues2.put("ANSWER", answer);
// Insert the row into your table
db2.insert("SURVEY1", null, newValues2);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName) {
//String id=String.valueOf(ID);
String where = "USERNAME=?";
int numberOFEntriesDeleted = db2.delete("LOGIN", where, new String[]{UserName});
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String[] getQuestion() {
final String TABLE_NAME = "QUESTION";
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getDatabaseInstance();
Cursor cursor = db2.rawQuery(selectQuery, null);
String[] data = null;
if(cursor.moveToFirst()) {
do {
// get the data into the array, or class variable
}while (cursor.moveToNext());
}
cursor.close();
return data;
}
public String getSingleEntry()
{
Cursor cursor=db2.query("QUESTION", null, null, null, null, null, null);
cursor.moveToFirst();
String question= cursor.getString(cursor.getColumnIndex("QUESTION"));
cursor.close();
return question;
}
public void updateEntry(String userName, String password) {
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD", password);
String where = "USERNAME = ?";
db2.update("LOGIN", updatedValues, where, new String[]{userName});
}
}
CreateSurveyActivity.java
package com.example.david.myview3;
/**
* Created by David on 23/03/2017.
*/
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
public class CreateSurveyActivity extends DashBoardAppActivity {
EditText editQuestion, editAnswer1, editAnswer2, editAnswer3;
Button btnNext, btnComplete;
SurveyDataBaseAdapter SurveyDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoalbum);
// get Instance of Database Adapter
SurveyDataBaseAdapter = new SurveyDataBaseAdapter(this);
SurveyDataBaseAdapter = SurveyDataBaseAdapter.open();
// Get References of Views
editQuestion = (EditText) findViewById(R.id.editTextQuestion);
editAnswer1 = (EditText) findViewById(R.id.editTextAnswer1);
editAnswer2 = (EditText) findViewById(R.id.editTextAnswer2);
editAnswer3 = (EditText) findViewById(R.id.editTextAnswer3);
// Get Refs of buttons
btnComplete = (Button) findViewById(R.id.buttonSignUP);
}
public void createSurvey(View V){
final Dialog dialog = new Dialog(CreateSurveyActivity.this);
dialog.setContentView(R.layout.photoalbum);
dialog.setTitle("Create");
// get the Refferences of views
final EditText editQuestion=(EditText)dialog.findViewById(R.id.editTextQuestion);
editQuestion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
final EditText editAnswer1=(EditText)dialog.findViewById(R.id.editTextAnswer1);
editAnswer1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
final EditText editAnswer2=(EditText)dialog.findViewById(R.id.editTextAnswer2);
editAnswer2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
final EditText editAnswer3=(EditText)dialog.findViewById(R.id.editTextAnswer3);
editAnswer3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
// Set On ClickListener
Button btnNext = (Button) dialog.findViewById(R.id.buttonNext);
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String question = editQuestion.getText().toString();
String answer1 = editAnswer1.getText().toString();
String answer2 = editAnswer2.getText().toString();
String answer3 = editAnswer3.getText().toString();
// check if any of the fields are vaccant
if (question.equals("") || answer1.equals("") || answer2.equals("") || answer3.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
{
// Save the Data in Database
SurveyDataBaseAdapter.insertQuestion(question, answer1, answer2, answer3);
Toast.makeText(getApplicationContext(), "Question Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
// try to send home on complete button press
//*
//btnNext = (Button) findViewById(R.id.buttonNext);
// btnNext.setOnClickListener(new View.OnClickListener() {
// final Intent intent = new Intent(context, DashHomeActivity.class);
//
// });
}
public void hideKeyboard(View view){
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
SurveyDataBaseAdapter.close();
}
}
logcat -
04-17 20:26:41.408 14322-14322/com.example.david.myview3 E/SQLiteLog: (1) no such table: QUESTION
04-17 20:26:41.408 14322-14322/com.example.david.myview3 E/SQLiteDatabase: Error inserting ...
android.database.sqlite.SQLiteException: no such table: QUESTION (code 1): , while compiling: INSERT INTO QUESTION(QUESTION,ANSWER3,ANSWER2,ANSWER1) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:919)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:530)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1547)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1404)
at com.example.david.myview3.SurveyDataBaseAdapter.insertQuestion(SurveyDataBase Adapter.java:59)
at com.example.david.myview3.CreateSurveyActivity$5.onClick(CreateSurveyActivity .java:117)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:10 28)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Use SurveyDataBaseAdapter.DATABASE_CREATE1 instead of LoginDataBaseAdapter.DATABASE_CREATE1.
In your DataBaseHelper2.java, update onCreate() method as below:
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE1);
_db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE2);
_db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE3);
}
In your SurveyDataBaseAdapter , update SQL table create statement as below:
static final String DATABASE_CREATE1 = "CREATE TABLE " + "USER" + "( " +
"ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ID1 INTEGER, " + "NAME TEXT " + ")";
static final String DATABASE_CREATE2 = "CREATE TABLE " + "QUESTION" + "( " +
"ID2 INTEGER PRIMARY KEY AUTOINCREMENT, " +
"QUESTION TEXT, " + "ANSWER1 TEXT, " + "ANSWER2 TEXT, " + "ANSWER3 TEXT " + ")";
static final String DATABASE_CREATE3 = "CREATE TABLE " + "RESPONSE" + "( " +
"ID3 INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ID INTEGER, " + "QUESTION TEXT, " + "ANSWER INTEGER " + ")";

Copy and display data from one sqlite table to another at runtime

I am trying to make an android application that allows the user to create a custom workout list from an already existing list of workouts. I decided to create an sqlite database to accomplish this task. In my database handler class "DBHandles.java" I have created and populated "Table_Workouts" with all the available workouts in the application. Also in "DBHandles.java" I have created another empty table "Table_User_List" for the purpose of holding specific entries from the "Table_Workouts" table that the user selects. "Table_User_List" needs to be populated at runtime.
public class DBhandles extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Workouts.db";
public static final String TABLE_WORKOUTS = "Workouts";
public static final String TABLE_USER_LIST = "UserWorkouts";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_LINK = "link";
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_WORKOUTS_TABLE = "CREATE TABLE " +
TABLE_WORKOUTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
String CREATE_USER_TABLE ="CREATE TABLE " +
TABLE_USER_LIST + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
db.execSQL(CREATE_WORKOUTS_TABLE);
db.execSQL(CREATE_USER_TABLE);
db.execSQL("INSERT INTO " + TABLE_WORKOUTS + "(name, description, link) VALUES ('Shoulder Press', 'Shoulder PRess description', 'https://www.youtube.com/watch?v=qEwKCR5JCog')");
public void addWorkout(Workout workout) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, workout.getWorkoutName());
values.put(COLUMN_DESCRIPTION, workout.getDescription());
values.put(COLUMN_LINK, workout.getLink());
db.insert(TABLE_USER_LIST, null, values);
} catch (Exception e){
Log.d(TAG, "Error while trying to add");
}
finally{
db.endTransaction();
}
//db.close();
}
public Workout findWorkout(String Workoutname) {
String query = "SELECT * FROM " + TABLE_WORKOUTS
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
workout.setID(Integer.parseInt(cursor.getString(0)));
workout.setWorkoutName(cursor.getString(1));
workout.setDescription((cursor.getString(2)));
workout.setLink(cursor.getString(3));
cursor.close();
} else {
workout = null;
}
db.close();
return workout;
}
public boolean deleteWorkout(String Workoutname) {
boolean result = false;
String query = " SELECT * FROM " + TABLE_USER_LIST
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
workout.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_WORKOUTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(workout.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
public ArrayList getAllWorkoutNames (){
return genericGetSQL(TABLE_WORKOUTS, COLUMN_NAME);
}
public ArrayList genericGetSQL(String whichTable, String whichColumn){
ArrayList<String> wrkArray = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(whichTable, new String[]{whichColumn}, null,null, null, null,null);
String fieldToAdd = null;
if(cursor.moveToFirst()){
while(cursor.isAfterLast()==false){
fieldToAdd = cursor.getString(0);
wrkArray.add(fieldToAdd);
cursor.moveToNext();
}
cursor.close();
}
return wrkArray;
}
As you can see I am returning an Arraylist from the DBHandles.class to display the name column of the "Table_Workouts" table. This ArrayList is accessed in my "DisplayAllWorkouts.java" class. The "DiplayAllWorkouts.java" class generates a tablerow for each entry in the "Table_Workouts" table and displays the name column to the user.
public class DisplayAllWorkouts extends AppCompatActivity implements YourListFrag.OnFragmentInteractionListener {
DBhandles db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayworkoutlist);
yourListFrag = new YourListFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.LinLayDisplayYourList, yourListFrag, "ARG_PARAM1").
commit();
context = this;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText = {"NAME ", " ADD "};
for (String c : headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
db = yourListFrag.getDb();//new DBhandles(this, null, null, 1);
final ArrayList<String> arrNames = db.getAllWorkoutNames();
final ArrayList<String> arrDesc = db.getAllWorkoutDescription();
final ArrayList<String> arrLink = db.getAllWorkoutsLink();
for (int i = 0; i < arrNames.size(); i++) {
TableRow row = new TableRow(this);
final CheckBox AddBox = new CheckBox(this);
AddBox.setText("ADD");
final TextView nametv = new TextView(this);
//final TextView desctv = new TextView(this);
//final TextView linktv = new TextView(this);
nametv.setTextSize(30);
// desctv.setTextSize(30);
nametv.setText(arrNames.get(i));
//desctv.setText(arrDesc.get(i));
//linktv.setText(arrLink.get(i));
text = nametv.getText().toString();
row.addView(nametv);
row.addView(AddBox);
AddBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// if(AddBox.isChecked()){
Workout wrk = (db.findWorkout(text));
db.addWorkout(wrk);
yourListFrag.refresh();
// yourListFrag.refresh();
// yourListFrag.refresh(text);
// }
// else{
// db.deleteWorkout(text);
//yourListFrag.delete(nametv.getText().toString());
// yourListFrag.refresh();
// }
}
});
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DisplayAllWorkouts.this, DisplaySingleWorkout.class);
i.putExtra("itemName", nametv.getText());
i.putStringArrayListExtra("everydesc", arrDesc);
i.putStringArrayListExtra("everyname", arrNames);
i.putStringArrayListExtra("everylink",arrLink);
startActivity(i);
}
});
tableLayout.addView(row);
}
}
#Override
public void onFragmentInteraction(int position) {
}
}
My problem is as follows. I want to be able to click on a table row displayed in the "DisplayAllWorkouts.java" class and have the corresponding row in "Table_Workouts" table be copied to the "Table_User_List" table. Once the row is copied I want the name column of "Table_User_List" displayed in "YourListFrag.java" class and inflated in the "DisplayAllWorkouts.java" class.
public class YourListFrag extends Fragment {
private ArrayAdapter<String> arrayAdapter;
private ListView lstView;
public ArrayList<String> holdNamesFromDB;
final DBhandles db = new DBhandles(getContext(), null, null, 1);
public DBhandles getDb(){
return this.db;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_list, container, false);
lstView = (ListView)rootView.findViewById(R.id.lstView);
holdNamesFromDB = db.getAllUserWorkouts();
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, holdNamesFromDB);
lstView.setAdapter(arrayAdapter);
public void refresh(){//String text){
//arrayAdapter.add(text);
// db.getAllUserWorkouts();
// arrayAdapter.notifyDataSetChanged();
holdNamesFromDB = db.getAllUserWorkouts();
//arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, db.getAllUserWorkouts());
arrayAdapter.notifyDataSetChanged();
// arrayAdapter.notifyDataSetChanged();
//
}
I need the fragment to refresh its view everytime a new entry is added to the "Table_User_List" so the user can see every entry of the name column of "Table_User_List" in real time. I put logs in my program and the the flow seemed to successfully reach all the appropriate method calls without throwing an error or crashing. However, my program does not display the entries from Table_User_List in the "YourListFrag.java" class. I don't know if their is a problem copying the row from one sqlite table to the other, displaying and refershing the name column in the fragment or inflating the fragment into "DisplayAllWorkouts.java" class. I have been struggling with this problem for awhile now and I finally decided to reach out to the community that has always been there for me. I have referenced the following sqlite copy data from one table to another
and i can't tell if this approach actually works in my program because nothing is displayed in the fragment. Thank you for your time and effort. I apologize for the lines of code i commented out and posted. I have been trying everything i could think of.

Change SQLite query on dependant on Spinner row

I am fetching information from a SQLite database and displaying it via a list view. Above the list view i have a spinner with various options created in XML:
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:entries="#array/catergory_arrays" />
Array of spinner values:
<string-array name="catergory_arrays">
<item>Select category here:</item>
<item>Fridge / Freezer</item>
<item>Canned Food</item>
<item>Fruit</item>
<item>Vegetable</item>
</string-array>
Dependent on the position of the spinner i want to set a different query which is then shown in the listview. Current code:
Class to show database information (CurrentItems):
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
int spinnerID;
// the table that displays the data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_inventory);
db = new ItemDatabase(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
displaySearch();
}
private void setupViews() {
// bring up current database items
listView = (ListView) findViewById(R.id.dbListView);
// THE BUTTONS
addButton = (Button) findViewById(R.id.scanCurrent);
editButton = (Button) findViewById(R.id.editItemCurrent);
}
private void addButtonListeners() {
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, AddItem.class));
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, EditItems.class));
}
});
}
public int getSelectedItemPosition() {
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
return spinnerID;
}
private void displaySearch() {
// TODO Auto-generated method stub
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
String catSelected;
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> itemArray;
itemArray = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
{
if (getSelectedItemPosition() == 0) {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 1) {
catSelected = "Fridge";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 2) {
catSelected = "Can";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 3) {
catSelected = "Fruit";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else if (getSelectedItemPosition() == 4) {
catSelected = "Vegetable";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
} else {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString())
+ "\nCategory:" + row.get(3).toString() + "\n");
itemArray.notifyDataSetChanged();
listView.setAdapter(itemArray);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
ItemDatabase:
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public final class ItemDatabase {
// the Activity or Application that is creating an object from this class.
Context context;
// a reference to the database used by this application/object
private SQLiteDatabase db;
// These constants are specific to the database.
private final String DATABASE_NAME = "ItemDatabase.sqlite";
private final int DATABASE_VERSION = 5;
// These constants are specific to the database table.
private final String TABLE_NAME = "foodItems";
private final String COLUMN_NAME_ENTRY_ID = "entryid";
private final String COLUMN_NAME_BARCODE = "barcode";
private final String COLUMN_NAME_TITLE = "title";
private final String COLUMN_NAME_QUANTITY = "quantity";
private final String COLUMN_NAME_DATE = "date";
private final String COLUMN_NAME_CATEGORY = "category";
String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
+ COLUMN_NAME_ENTRY_ID
+ " integer primary key autoincrement not null," + COLUMN_NAME_DATE
+ " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
+ " text," + COLUMN_NAME_QUANTITY + " int," + COLUMN_NAME_CATEGORY + " text" + ");";
public ItemDatabase(Context context) {
this.context = context;
// create or open the database
ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo,
String rowStringThree, String rowStringFour, int rowIntFive) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_CATEGORY, rowStringFour);
values.put(COLUMN_NAME_QUANTITY, rowIntFive);
// ask the database object to insert the new data
try {
db.insert(TABLE_NAME, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to update the database row of given rowID
try {
db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
null);
} catch (Exception e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID) {
// ask the database manager to delete the row of given id
try {
db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
getAllRowsAsArrays();
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public ArrayList<ArrayList<Object>> getCategoryOfArrays(String category) {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, COLUMN_NAME_CATEGORY + "='" + category + "'", null,
null, null, COLUMN_NAME_TITLE + " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
while (cursor.moveToNext()) {
// your content
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CATEGORY)));
dataArrays.add(dataList);
}
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, null, null,
null, null, COLUMN_NAME_TITLE + " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
while (cursor.moveToNext()) {
// your content
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CATEGORY)));
dataArrays.add(dataList);
}
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// execute the query string to the database.
db.execSQL(SQL_CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade
// policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
}
Have tested getCategoryOfArrays() and it works. Current code doesn't return any errors however Spinner action does not change the listview contents.
All help will be appreciated!
Your method displaySearch() is only called once, at Activity creation, when the spinner is at position zero. In onCreate (perhaps within your addButtonListeners() method) set a listener on the spinner for when the value changes. When it does, call displaySearch() again.
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
selectCat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
displaySearch();
}
public void onNothingSelected(AdapterView<?> parent)
{
// Do nothing
}
});

Categories

Resources