Display SQLite information via CUSTOM listview - java

I have a working sqlite database which items can be added to and viewed via a listview. I now want to add a edit/delete button to each view dynamically.
Following the tutorial http://looksok.wordpress.com/2012/11/03/android-custom-listview-tutorial/ I have created a custom XML file with an edit/delete button. I am however unable to follow the tutorial as it does not show for retrieving and displaying sqlite information.
XML layout for custom list view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText
android:id="#+id/itemName"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="2"
android:gravity="center_vertical"
android:hint="#string/title"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/itemQuantity"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:inputType="numberDecimal"
android:text="#string/quantity"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageButton
android:id="#+id/editItem"
android:layout_width="#dimen/width_button"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name"
android:onClick="editOnClick"
android:src="#android:drawable/ic_menu_edit" />
<ImageButton
android:id="#+id/deleteItem"
android:layout_width="#dimen/width_button"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name"
android:onClick="removeOnClick"
android:src="#android:drawable/ic_menu_delete" />
</LinearLayout>
Current Inventory XML (Where listview is shown):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/currentInventory"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
xmlns:tools="http://schemas.android.com/tools" >
<TextView android:layout_marginTop="5dip"
android:id="#+id/selectCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/selectCategory"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/catergory_arrays" />
<ListView
android:id="#+id/customDbListView"
android:layout_width="match_parent"
android:layout_height="350dip"
android:layout_marginBottom="20dip"
android:layout_marginTop="20dip"
tools:listitem="#layout/list_view_custom" >
</ListView>
<Button
android:id="#+id/scanCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="5dip"
android:text="#string/scan" />
<Button
android:id="#+id/editItemCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:text="#string/editItem" />
</LinearLayout>
Creation of database:
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public final class ItemDatabase {
// the Activity or Application that is creating an object from this class.
Context context;
// a reference to the database used by this application/object
private SQLiteDatabase db;
// These constants are specific to the database.
private final String DATABASE_NAME = "ItemDatabase.sqlite";
private final int DATABASE_VERSION = 7;
// These constants are specific to the database table.
private final String TABLE_NAME = "foodItems";
private final String COLUMN_NAME_ENTRY_ID = "entryid";
private final String COLUMN_NAME_BARCODE = "barcode";
private final String COLUMN_NAME_TITLE = "title";
private final String COLUMN_NAME_QUANTITY = "quantity";
private final String COLUMN_NAME_DATE = "date";
private final String COLUMN_NAME_CATEGORY = "category";
String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
+ COLUMN_NAME_ENTRY_ID
+ " integer primary key autoincrement not null," + COLUMN_NAME_DATE
+ " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
+ " text," + COLUMN_NAME_QUANTITY + " int," + COLUMN_NAME_CATEGORY
+ " text" + ");";
public ItemDatabase(Context context) {
this.context = context;
// create or open the database
ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo,
String rowStringThree, String rowStringFour, int rowIntFive) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_CATEGORY, rowStringFour);
values.put(COLUMN_NAME_QUANTITY, rowIntFive);
// ask the database object to insert the new data
try {
db.insert(TABLE_NAME, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to update the database row of given rowID
try {
db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
null);
} catch (Exception e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID) {
// ask the database manager to delete the row of given id
try {
db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
getAllRowsAsArrays();
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public ArrayList<ArrayList<Object>> getCategoryOfArrays(String category) {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY,
COLUMN_NAME_CATEGORY }, COLUMN_NAME_CATEGORY + "='"
+ category + "'", null, null, null, COLUMN_NAME_TITLE
+ " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor
.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor
.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor
.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataArrays.add(dataList);
} while (cursor.moveToNext());
}
// let java know that you are through with the cursor.
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_TITLE,
COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, null, null,
null, null, COLUMN_NAME_TITLE + " ASC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getString(cursor
.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor
.getColumnIndex(COLUMN_NAME_QUANTITY)));
dataArrays.add(dataList);
} while (cursor.moveToNext());
}
// let java know that you are through with the cursor.
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// execute the query string to the database.
db.execSQL(SQL_CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade
// policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
}
Current code to display database data:
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
int spinnerID;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_inventory);
db = new ItemDatabase(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
// display search results
displaySearch();
}
private void setupViews() {
// bring up current database items
listView = (ListView) findViewById(R.id.customDbListView);
// THE BUTTONS
addButton = (Button) findViewById(R.id.scanCurrent);
editButton = (Button) findViewById(R.id.editItemCurrent);
}
private void addButtonListeners() {
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
selectCat
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
displaySearch();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing
}
});
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, AddItem.class));
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, EditItems.class));
}
});
}
public int getSelectedItemPosition() {
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
return spinnerID;
}
private void displaySearch() {
// TODO Auto-generated method stub
Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
spinnerID = selectCat.getSelectedItemPosition();
String catSelected;
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> itemArray;
itemArray = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
{
if (getSelectedItemPosition() == 0) {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nTitle: " + row.get(0).toString()
+ "\nQuantity: " + row.get(1).toString() + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 1) {
catSelected = "Fridge";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 2) {
catSelected = "Can";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 3) {
catSelected = "Fruit";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else if (getSelectedItemPosition() == 4) {
catSelected = "Vegetable";
ArrayList<ArrayList<Object>> data = db
.getCategoryOfArrays(catSelected);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate: " + row.get(0).toString()
+ "\nTitle: " + row.get(1).toString()
+ "\nQuantity: "
+ Integer.parseInt(row.get(2).toString()) + "\n");
itemArray.notifyDataSetChanged();
}
listView.setAdapter(itemArray);
} else {
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nTitle: " + row.get(0).toString()
+ "\nQuantity: " + row.get(1).toString() + "\n");
itemArray.notifyDataSetChanged();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
The current code as it stands will only display the data as a regular listview. I need the data to show as:
Title Quantity (EditButton) (DeleteButton)
All help will be appreciated!
Thanks

As i was a little bored i took the liberty to implement the adapter. You will have to edit the way you retrieve your elements from the db and how the Classes Information is Accessed since you didnt post the corresponding class representation.
You could however implement a CursorAdapter instead of a BaseAdapter.
public class QuantatiyAdapter extends BaseAdapter {
private Context context;
private List<Item> data;
public QuantatiyAdapter(Context context) {
this.context = context;
//TODO actually put all your data into that list.
this.data = Database.getAllData();
}
#Override
public int getCount() {
return this.data.size();
}
#Override
public Object getItem(int arg0) {
return this.data.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View converView, ViewGroup container) {
ViewHolder holder = null;
if (converView == null) {
converView = LayoutInflater.from(context).inflate(R.layout.cutomLayout, null);
holder = new ViewHolder();
holder.title = (TextView) converView.findViewById(R.id.itemName);
holder.quantity = (TextView) converView.findViewById(R.id.itemQuantity);
holder.edit = (ImageButton) converView.findViewById(R.id.editItem);
holder.delete = (ImageButton) converView.findViewById(R.id.deleteItem);
converView.setTag(holder);
} else {
holder = (ViewHolder) converView.getTag();
}
// filling text
holder.title.setText(getItem(position).getTitle());
// adding action listeners to buttons
holder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO fill methods for buttons
}
});
return converView;
}
private static class ViewHolder {
TextView title,quantity;
ImageButton edit,delete;
}
}

Related

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.

Flickering of ListView item if deleting asynchronously

I am trying to remove a ListView item from it asynchronously with a slide animation by using a Content Provider and CursorAdapter, but as I am removing the item by calling a method in Content Provider, the deleted view with deleted data reappears on the screen. The data itself is correctly deleted from the database, but I am not able to fix the flickering issue of deleted view. If I use synchronous deleting from database, the flickering issue is not present. I have tried to implement solution, which have been proposed in the following articles, but couldn't solve the issue:
Correctly animate removing row in ListView?
CursorAdapter backed ListView delete animation "flickers" on delete
I am posting an example of the code to make the issue more empirical. Any help would be appreciated a lot :).
Class AndroidListViewCursorAdaptorActivity:
package com.example.keit.mytestapp;
import android.app.Activity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.keit.mytestapp.contentprovider.CustomContentProvider;
public class AndroidListViewCursorAdaptorActivity extends Activity implements android.app.LoaderManager.LoaderCallbacks<Cursor> {
private CountriesDbAdapter dbHelper;
private MyCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbHelper = new CountriesDbAdapter(this);
dbHelper.open();
//Clean all data
dbHelper.deleteAllCountries();
//Add some data
dbHelper.insertSomeCountries();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCountries();
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code
};
ListView listView = (ListView) findViewById(R.id.listView1);
// CursorLoader and CursorAdapter are initialized.
getLoaderManager().initLoader(0, null, this);
dataAdapter = new MyCursorAdapter(this, null, 1, listView) {
#Override
public void deleteRow(long id) {
Log.i("DELETE", "Country code: " + id);
//dbHelper.deleteCountry(id);
Uri uri = Uri.parse(CustomContentProvider.CONTENT_URI + "/"
+ id);
getContentResolver().delete(uri, null, null);
}
};
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
dataAdapter.setSelectedItemId(id);
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
}
// Creates a new loader after the initLoader () call.
#Override
public android.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
CountriesDbAdapter.KEY_ROWID,
CountriesDbAdapter.KEY_CODE,
CountriesDbAdapter.KEY_NAME,
CountriesDbAdapter.KEY_CONTINENT,
CountriesDbAdapter.KEY_REGION
};
CursorLoader cursorLoader = new CursorLoader(this,
CustomContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(android.content.Loader<Cursor> loader, Cursor cursor) {
dataAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(android.content.Loader<Cursor> loader) {
dataAdapter.swapCursor(null);
}
}
Class CustomerContentProvider in package "contentprovider":
package com.example.keit.mytestapp.contentprovider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.example.keit.mytestapp.CountriesDbAdapter;
import com.example.keit.mytestapp.DatabaseHelper;
public class CustomContentProvider extends android.content.ContentProvider {
// database
private SQLiteOpenHelper dbHelper;
// used for the UriMacher
private static final int DEBTS = 10;
private static final int DEBT_ID = 20;
private static final String AUTHORITY = "com.example.keit.mytestapp.contentprovider";
private static final String BASE_PATH = "mytestapp";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/mytestapp";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/countries";
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, BASE_PATH, DEBTS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", DEBT_ID);
}
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Using SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// Set the table
queryBuilder.setTables(CountriesDbAdapter.SQLITE_TABLE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case DEBTS:
break;
case DEBT_ID:
// adding the ID to the original query
queryBuilder.appendWhere(CountriesDbAdapter.KEY_ROWID + "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
// make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
int rowsDeleted = 0;
long id = 0;
switch (uriType) {
case DEBTS:
id = sqlDB.insert(CountriesDbAdapter.SQLITE_TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case DEBTS:
rowsDeleted = sqlDB.delete(CountriesDbAdapter.SQLITE_TABLE, selection,
selectionArgs);
Log.i("MyActivity", "DEBTS ");
break;
case DEBT_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = sqlDB.delete(CountriesDbAdapter.SQLITE_TABLE,
CountriesDbAdapter.KEY_ROWID + "=" + id,
null);
Log.i("MyActivity", "DEBT_ID");
} else {
rowsDeleted = sqlDB.delete(CountriesDbAdapter.SQLITE_TABLE,
CountriesDbAdapter.KEY_ROWID + "=" + id
+ " and " + selection,
selectionArgs);
Log.i("MyActivity", "ELSE");
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case DEBTS:
rowsUpdated = sqlDB.update(CountriesDbAdapter.SQLITE_TABLE,
values,
selection,
selectionArgs);
break;
case DEBT_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(CountriesDbAdapter.SQLITE_TABLE,
values,
CountriesDbAdapter.KEY_ROWID + "=" + id,
null);
} else {
rowsUpdated = sqlDB.update(CountriesDbAdapter.SQLITE_TABLE,
values,
CountriesDbAdapter.KEY_ROWID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
}
Class CountriesDbAdapter:
package com.example.keit.mytestapp;
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 class CountriesDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_CODE = "code";
public static final String KEY_NAME = "name";
public static final String KEY_CONTINENT = "continent";
public static final String KEY_REGION = "region";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String DATABASE_NAME = "World";
public static final String SQLITE_TABLE = "Country";
public static final int DATABASE_VERSION = 1;
private final Context mCtx;
public static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_CODE + "," +
KEY_NAME + "," +
KEY_CONTINENT + "," +
KEY_REGION + "," +
" UNIQUE (" + KEY_CODE +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCountry(String code, String name,
String continent, String region) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CODE, code);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_CONTINENT, continent);
initialValues.put(KEY_REGION, region);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public void deleteCountry (long id) {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, "_id" + "=" + id , null);
}
public boolean deleteAllCountries() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCountriesByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCountries() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeCountries() {
createCountry("AFG","Afghanistan","Asia","Southern and Central Asia");
createCountry("ALB","Albania","Europe","Southern Europe");
createCountry("DZA","Algeria","Africa","Northern Africa");
createCountry("ASM","American Samoa","Oceania","Polynesia");
createCountry("AND","Andorra","Europe","Southern Europe");
createCountry("AGO","Angola","Africa","Central Africa");
createCountry("AIA","Anguilla","North America","Caribbean");
}
}
Class MyCursorAdapter:
package com.example.keit.mytestapp;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import java.util.HashMap;
public class MyCursorAdapter extends CursorAdapter {
private long selectedItemId;
private long previouslySelectedItemId;
private ListView adapterListView;
private static final int MOVE_DURATION = 300;
HashMap<Long, Integer> mItemIdTopMap = new HashMap<Long, Integer>();
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
// A customer constructor for passing ListView inside a view in addition to default parameters.
public MyCursorAdapter(Context context, Cursor cursor, int flags, ListView listView) {
super(context, cursor, 0);
adapterListView = listView;
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.country_info, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, final Context context, Cursor cursor) {
TextView countryCodeView = (TextView) view.findViewById(R.id.code);
String countryCode = cursor.getString(cursor.getColumnIndexOrThrow(CountriesDbAdapter.KEY_CODE));
countryCodeView.setText(countryCode);
// Listener is created for "Delete" button.
ImageButton deleteItem = (ImageButton) view.findViewById(R.id.delete_item);
deleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Log.i("onClick", "Executed");
adapterListView.requestDisallowInterceptTouchEvent(true); // Will disallow touch events.
adapterListView.setEnabled(false); // Will disable list view (e.g. to avoid scrolling).
final View activeView = (View) view.getParent(); //ListView item parent view is returned.
if (activeView != null) {
long duration = 800;
float endX = activeView.getWidth();
float endAlpha = 0; // Opacity will be set to 0.
activeView.animate().setDuration(duration).
alpha(endAlpha).translationX(endX).
withEndAction(new Runnable() {
#Override
public void run() {
activeView.setAlpha(1);
activeView.setTranslationX(0);
animateRemoval(adapterListView, activeView);
}
});
Log.i("FAFA", "Animation ended");
// notifyDataSetChanged();
}
}
});
}
// The method sets a global temporary value of selected item's id.
public void setSelectedItemId(long id) {
previouslySelectedItemId = selectedItemId;
selectedItemId = id;
}
// The method returns a global temporary value of selected item's id.
public long getSelectedItemId() {
return selectedItemId;
}
/**
* The method will be always be overwritten by calling class to handle database manipulation in activity.
* #param id
*/
public void deleteRow(long id) {
}
private void animateRemoval(final ListView listview, final View viewToRemove) {
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
View child = listview.getChildAt(i);
if (child != viewToRemove) {
int position = firstVisiblePosition + i;
long itemId = getItemId(position);
mItemIdTopMap.put(itemId, child.getTop());
}
}
final int position = adapterListView.getPositionForView(viewToRemove);
final ViewTreeObserver observer = listview.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
observer.removeOnPreDrawListener(this);
boolean firstAnimation = true;
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
final View child = listview.getChildAt(i);
int position = firstVisiblePosition + i;
long itemId = getItemId(position);
Integer startTop = mItemIdTopMap.get(itemId);
int top = child.getTop();
if (startTop != null) {
if (startTop != top) {
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
child.animate().withEndAction(new Runnable() {
public void run() {
listview.requestDisallowInterceptTouchEvent(false); // Will allow touch events.
listview.setEnabled(true); // Will enable list view (e.g. to avoid scrolling).
}
});
firstAnimation = false;
}
}
} else {
// Animate new views along with the others. The catch is that they did not
// exist in the start state, so we must calculate their starting position
// based on neighboring views.
int childHeight = child.getHeight() + listview.getDividerHeight();
startTop = top + (i > 0 ? childHeight : -childHeight);
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
child.animate().withEndAction(new Runnable() {
public void run() {
listview.requestDisallowInterceptTouchEvent(false); // Will allow touch events.
listview.setEnabled(true); // Will enable list view (e.g. to avoid scrolling).
}
});
firstAnimation = false;
}
}
}
CustomCursorWrapper cursorWrapper = new CustomCursorWrapper(getCursor(), position);
swapCursor(cursorWrapper);
deleteRow(selectedItemId);
mItemIdTopMap.clear();
return true;
}
});
}
}
Class CustomCursorWrapper:
package com.example.keit.mytestapp;
import android.database.Cursor;
import android.database.CursorWrapper;
public class CustomCursorWrapper extends CursorWrapper
{
private int mVirtualPosition;
private int mHiddenPosition;
public CustomCursorWrapper(Cursor cursor, int hiddenPosition)
{
super(cursor);
mVirtualPosition = -1;
mHiddenPosition = hiddenPosition;
}
#Override
public int getCount()
{
return super.getCount() - 1;
}
#Override
public int getPosition()
{
return mVirtualPosition;
}
#Override
public boolean move(int offset)
{
return moveToPosition(getPosition() + offset);
}
#Override
public boolean moveToFirst()
{
return moveToPosition(0);
}
#Override
public boolean moveToLast()
{
return moveToPosition(getCount() - 1);
}
#Override
public boolean moveToNext()
{
return moveToPosition(getPosition() + 1);
}
#Override
public boolean moveToPosition(int position)
{
mVirtualPosition = position;
int cursorPosition = position;
if (cursorPosition >= mHiddenPosition)
{
cursorPosition++;
}
return super.moveToPosition(cursorPosition);
}
#Override
public boolean moveToPrevious()
{
return moveToPosition(getPosition() - 1);
}
#Override
public boolean isBeforeFirst()
{
return getPosition() == -1 || getCount() == 0;
}
#Override
public boolean isFirst()
{
return getPosition() == 0 && getCount() != 0;
}
#Override
public boolean isLast()
{
int count = getCount();
return getPosition() == (count - 1) && count != 0;
}
#Override
public boolean isAfterLast()
{
int count = getCount();
return getPosition() == count || count == 0;
}
}
Class DatabaseHelper:
package com.example.keit.mytestapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public DatabaseHelper(Context context) {
super(context, CountriesDbAdapter.DATABASE_NAME, null, CountriesDbAdapter.DATABASE_VERSION);
}
// Creates SQL Lite database tables
public void onCreate(SQLiteDatabase db) {
db.execSQL(CountriesDbAdapter.DATABASE_CREATE);
}
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(DatabaseContract.Debts.SQL_DELETE_TABLE);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
country_info.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="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants"
android:background="#android:color/darker_gray"
android:padding="6dip">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Code: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageButton
android:id="#+id/delete_item"
android:layout_width="40dp"
android:layout_height="fill_parent"
android:scaleType="centerInside"
android:src="#mipmap/ic_launcher"
android:focusable="false"
android:focusableInTouchMode="false"
android:background="#android:color/transparent"/>
</LinearLayout>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/some_text" android:textSize="20sp" />
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

How to store and fetch list view data from sqlite in android?

I have created a simple demo in which I have simply stored the two value that is first name and last name in sqlite and display that in list view.But when I tried two add more value like phone no.address,state,country etc . I got error.and it display the message like could not read the row and column data.
please help me two add 9 or 10 value and display in list view.here is my code.
AddActivity.Java
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,phoneNo;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,pno;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
phoneNo=(EditText)findViewById(R.id.phoneNo);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
pno=getIntent().getExtras().getString("Pno");
edit_first.setText(fname);
edit_last.setText(lname);
phoneNo.setText(pno);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
pno=phoneNo.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_PHONENO,pno );
System.out.println("");
if(isUpdate)
{
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
dataBase.close();
finish();
}
}
DisplayAdapter.java
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> phoneNo;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname,ArrayList<String> pno) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.phoneNo = pno;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.phoneTextView = (TextView) child.findViewById(R.id.phoneTextView);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.phoneTextView.setText(phoneNo.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView phoneTextView;
}
}
Database Helper.java
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_PHONENO="pno";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_PHONENO+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
DisplayActivity.java
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_phoneNo = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("Lname", user_phoneNo.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+user_phoneNo.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_phoneNo.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_phoneNo.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PHONENO)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName,user_phoneNo);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Below is an example of storing and fetching data from database.
public class Database extends SQLiteOpenHelper {
public static final String KEY_ID= "id";
public static final String KEY_SURVEY_UPLOAD = "IS_SURVEY_UPLOAD";
public static final String KEY_SURVEY_COMPLETE = "IS_SURVEY_COMPLETE";
public static final String KEY_DEVICE_ID = "DEVICE_ID";
public static final String KEY_LATITUDE = "LATITUDE";
public static final String KEY_LONGITUDE = "LONGITUDE";
public static final String KEY_FILE_ID = "FILE_ID";
public static final String DATABASE_NAME = "DatabaseName";
public static final String DATABASE_TABLE_one = "Table1";
private static final String CREATE_TABLE__NUM = "create table "+DATABASE_TABLE_SURVEY+
" ("+KEY_SURVEY_COMPLETE+" TEXT,"+KEY_FILE_ID+" INTEGER,"+KEY_DEVICE_ID+" TEXT,"+KEY_LATITUDE+" TEXT, "+KEY_LONGITUDE+" TEXT, "+KEY_SURVEY_UPLOAD+" TEXT, "+KEY_SURVEYID+" INTEGER PRIMARY KEY AUTOINCREMENT )";
public Database(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
System.out.println("crteate table");
db.execSQL(CREATE_TABLE_SURVEY_CONTENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_one);
onCreate(db);
}
public boolean insertData(SurveyBean bean)
{
System.out.println("insert_SURVEY");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURVEY_COMPLETE, "false");
contentValues.put(KEY_SURVEY_UPLOAD, "0");
contentValues.put(KEY_LATITUDE, bean.getLatitude());
contentValues.put(KEY_LONGITUDE, bean.getLongitude());
contentValues.put(KEY_DEVICE_ID, bean.getDeviceId());
contentValues.put(KEY_FILE_ID, Integer.getInteger(bean.getFileId()));
long id=db.insert(DATABASE_TABLE_SURVEY, null, contentValues);
System.out.println("last inserted ID"+id);
db.close();
return true;
}
public ArrayList<SurveyBean> getAllData(){
ArrayList<SurveyBean> arrayList = new ArrayList<SurveyBean>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cc = db.rawQuery("SELECT *" + " FROM " + DATABASE_TABLE_SURVEY, null);
cc.moveToFirst();
while(cc.isAfterLast() == false){
SurveyBean bean = new SurveyBean();
bean.set_isSurveyComplete(cc.getString(cc.getColumnIndex(KEY_SURVEY_COMPLETE)));
bean.set_isSurveyUpload(cc.getString(cc.getColumnIndex(KEY_SURVEY_UPLOAD)));
bean.set_surveyId(Integer.parseInt(cc.getString(cc.getColumnIndex(KEY_SURVEYID))));
bean.setDeviceId(cc.getString(cc.getColumnIndex(KEY_DEVICE_ID)));
bean.setLatitude(cc.getString(cc.getColumnIndex(KEY_LATITUDE)));
bean.setLongitude(cc.getString(cc.getColumnIndex(KEY_LONGITUDE)));
bean.setFileId(String.valueOf(cc.getInt(cc.getColumnIndex(KEY_FILE_ID))));
arrayList.add(bean);
cc.moveToNext();
}
db.close();
return arrayList ;
}
}
Look i had done a simple app to create a list view from sqlite database in android. Have a look at it.It may help you.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "testdb";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "tbl_details";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
tableName +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('A','vijay','India',20);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('B','ajay','Pakistan',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C','suraj','Bangladesh',30);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D','jayesh','China',35);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('E','ramesh','Nepal',40);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('F','suresh','SriLanka',45);");
}
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ListViewFromSQLiteDB"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ListViewFromSQLiteDB.java
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
}

Delete a task in SQLite database

Hello I'm developing an app with a Task Viewer, I can add Tasks but no delete.
How I can delete them?
Another question: How I can change the message that appears when I click on the checkbox?
TaskerDbHelper
public class TaskerDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "taskerManager";
// tasks table name
private static final String TABLE_TASKS = "tasks";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TASKNAME = "taskName";
private static final String KEY_STATUS = "status";
public TaskerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
+ " TEXT, " + KEY_STATUS + " INTEGER)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
// Create tables again
onCreate(db);
}
// Adding new task
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName()); // task name
// status of task- can be 0 for not done and 1 for done
values.put(KEY_STATUS, task.getStatus());
// Inserting Row
db.insert(TABLE_TASKS, null, values);
db.close(); // Closing database connection
}
public List<Task> getAllTasks() {
List<Task> taskList = new ArrayList<Task>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setStatus(cursor.getInt(2));
// Adding contact to list
taskList.add(task);
} while (cursor.moveToNext());
}
// return task list
return taskList;
}
public void updateTask(Task task) {
// updating row
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName());
values.put(KEY_STATUS, task.getStatus());
db.update(TABLE_TASKS, values, KEY_ID + " = ?",new String[] {String.valueOf(task.getId())});
db.close();
}
ViewTask
public class ViewTask extends Activity {
protected TaskerDbHelper db;
List<Task> list;
MyAdapter adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
db = new TaskerDbHelper(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.list_inner_view, list);
ListView listTask = (ListView) findViewById(R.id.listView1);
listTask.setAdapter(adapt);
}
public void addTaskNow(View v) {
EditText t = (EditText) findViewById(R.id.editText1);
String s = t.getText().toString();
if (s.equalsIgnoreCase("")) {
Toast.makeText(this, "enter the task description first!!",
Toast.LENGTH_LONG);
} else {
Task task = new Task(s, 0);
db.addTask(task);
Log.d("tasker", "data added");
t.setText("");
adapt.add(task);
adapt.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_view_task, menu);
return true;
}
private class MyAdapter extends ArrayAdapter<Task> {
Context context;
List<Task> taskList = new ArrayList<Task>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<Task> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
/**
* This method will DEFINe what the view inside the list view will
* finally look like Here we are going to code that the checkbox state
* is the status of task and check box text is the task name
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBox chk = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_inner_view,
parent, false);
chk = (CheckBox) convertView.findViewById(R.id.chkStatus);
convertView.setTag(chk);
chk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task changeTask = (Task) cb.getTag();
changeTask.setStatus(cb.isChecked() == true ? 1 : 0);
db.updateTask(changeTask);
Toast.makeText(
getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG)
.show();
}
});
} else {
chk = (CheckBox) convertView.getTag();
}
Task current = taskList.get(position);
chk.setText(current.getTaskName());
chk.setChecked(current.getStatus() == 1 ? true : false);
chk.setTag(current);
Log.d("listener", String.valueOf(current.getId()));
return convertView;
}
}
Layout
<RelativeLayout 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"
tools:context=".ViewTask"
android:background="#drawable/fondo">
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:layout_alignBottom="#+id/button1"
android:layout_toLeftOf="#+id/button1">
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="14dp"
android:text="Afegir"
android:onClick="addTaskNow"
android:textSize="30dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1">
</ListView>
Use below code to delete particular task which is selected, just put this below code inside your delete button's click event.
int len = mListView.getCount();
SparseBooleanArray checked = listTask.getCheckedItemPositions();
(int i = 0; i < len; i++)
if (checked.get(i)) {
String[] delete = list.get(i);
String idString = delete[0];
long idLong = Long.valueOf(idString);
db.delete(idLong);
list.remove(i);
You need to get KEY_ID for the task which has been clicked and then call the remove method for that task. Remove method could be as below
public void task_delete_byID(int id){
db.delete(TABLE_TASKS, KEY_ID+"="+id, null);
}
for multiple records to be deleted, use looping while calling the "task_delete_byID" method.
hope this helps.

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