Hi guys I'm currently creating an Android Application on Eclipse through various online tutorials. I have got as far as creating a SQLite database and being able to manually input information - although I'm not quite sure how to delete the information yet. What I would like is for the user to click a button and then it will display the information that they have inputted on a profile page - at the moment it is only two fields. I have spent hours going through various tutorials and research and just can not seem to get it to work. If anybody has the time to have a look through my code and tell me how I should call the methods to add new data via a button then it would be greatly appreciated. I think I am loosing my mind. I also understand I may not have gone around the correct way of setting things up but I am still learning.
Here is my DatabaseHandler.java file
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_EMAIL, contact.getEmail()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setEmail(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_EMAIL, contact.getEmail());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And below is my page that so far just sends forced information to the database as you will see.
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Addrecord extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Dan", "dljbrown#icloud.com"));
db.addContact(new Contact("Pash", "pashj#hotmail.com"));
db.addContact(new Contact("Nigel", "Dancinboyforever#hotmail.com"));
db.addContact(new Contact("Jit", "Jit#hotmail.com"));
// Log.d("Delete: ", "Deleting..");
// db.deleteContact(new Contact("Dan", "dljbrown#icloud.com"));
// db.deleteContact(new Contact("Pash", "pashj#hotmail.com"));
// db.deleteContact(new Contact("Nigel",
// "Dancinboyforever#hotmail.com"));
// db.deleteContact(new Contact("Jit", "dljbrown#icloud.com"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName()
+ " ,Email: " + cn.getEmail();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
So instead of the information being passed straight to the database and displayed in the log like below I would like the user to of pressed a button from a previous page and I will display their information.
Thanks if anybody gets round to replying!!
Here is the activity that I currently link to the "Addrecord" activity, once "Page1" in the list view has been clicked then I would like it to display the users information (Sample info at the moment)
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Home extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
populateListView();
registerClickCallback();
}
public void populateListView() {
String[] homelist = { "Page1", "Page2", "Page3", "Page4", "Page5" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_home, homelist);
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setAdapter(adapter);
}
public void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// NOW COPY AND PASTE FOR ALL THE OTHERS
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
Intent myintent = new Intent(getApplicationContext(),
Addrecord.class);
startActivity(myintent);
}
if (position == 1) {
Intent myintent2 = new Intent(getApplicationContext(),
Pagetwo.class);
startActivity(myintent2);
}
if (position == 2) {
Intent myintent3 = new Intent(getApplicationContext(),
Pagethree.class);
startActivity(myintent3);
}
if (position == 3) {
Intent myintent4 = new Intent(getApplicationContext(),
Pagefour.class);
startActivity(myintent4);
}
if (position == 4) {
Intent myintent5 = new Intent(getApplicationContext(),
Pagefive.class);
startActivity(myintent5);
}
if (position == 5) {
Intent myintent6 = new Intent(getApplicationContext(),
Pagesix.class);
startActivity(myintent6);
}
}
});
}
Related
I was adding a list view to my database when in the end the database list view windows opens and crashes
Do you have any idea what this crash code mean? I can add code later if you need it
(Edit still no luck finding anything that could throw this command)
Can you check with a command any way?
Database form:
package com.example.laivumusis;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.example.laivumusis.KlausimuContracts.*;
import java.util.ArrayList;
import java.util.List;
public class KlausimynoDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Klausimynas.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public KlausimynoDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
KlausimuLentele.TABLE_NAME + " ( " +
KlausimuLentele._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KlausimuLentele.COLUMN_QUESTION + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION1 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION2 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION3 + " TEXT, " +
KlausimuLentele.COLLUMN_ANSWER_NR + " INTEGER" +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillKlausimuLentele();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + KlausimuLentele.TABLE_NAME);
onCreate(db);
}
public boolean addData (String pasirinkimas1){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KlausimuLentele.COLLUMN_OPTION1, pasirinkimas1);
long result = db.insert(KlausimuLentele.TABLE_NAME, null, contentValues);
if (result == -1){
return false;
}else{
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME,null );
return data;
}
private void fillKlausimuLentele() {
Klausimai q1 = new Klausimai("Kelintais metais buvo išleista java proogramavimo kalba?", "1991", "1995", "1989", 1);
addQuestion(q1);
Klausimai q2 = new Klausimai("Ar destytojas pasigailės mūsų?", "Priklauso nuo darbo", "Priklauso nuo pingų", "Prklauso nuo nuotaikos", 1);
addQuestion(q2);
Klausimai q3 = new Klausimai("Kai sunervina žaidimas koks geriausias būdas iš jo išeiti?", "Alt+F4", "Quit To desktop", "Ištraukti maitinimo laida",1);
addQuestion(q3);
Klausimai q4 = new Klausimai("A is correct again", "A", "B", "C", 1);
addQuestion(q4);
Klausimai q5 = new Klausimai("B is correct agian", "A", "B", "C", 2);
addQuestion(q5);
}
private void addQuestion(Klausimai klausimai) {
ContentValues cv = new ContentValues();
cv.put(KlausimuLentele.COLUMN_QUESTION, klausimai.getKlausimas());
cv.put(KlausimuLentele.COLLUMN_OPTION1, klausimai.getPasirinkimas1());
cv.put(KlausimuLentele.COLLUMN_OPTION2, klausimai.getPasirinkimas2());
cv.put(KlausimuLentele.COLLUMN_OPTION3, klausimai.getPasirinkimas3());
cv.put(KlausimuLentele.COLLUMN_ANSWER_NR, klausimai.getAtsakymoNr());
db.insert(KlausimuLentele.TABLE_NAME, null, cv);
}
public List<Klausimai> getAllQuestions() {
List<Klausimai> klausimuSarasas = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
Klausimai klausimai = new Klausimai();
klausimai.setKlausimas(c.getString(c.getColumnIndex(KlausimuLentele.COLUMN_QUESTION)));
klausimai.setPasirinkimas1(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION1)));
klausimai.setPasirinkimas2(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION2)));
klausimai.setPasirinkimas3(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION3)));
klausimai.setAtsakymoNr(c.getInt(c.getColumnIndex(KlausimuLentele.COLLUMN_ANSWER_NR)));
klausimuSarasas.add(klausimai);
} while (c.moveToNext());
}
c.close();
return klausimuSarasas;
}
}
But i think the problem is in here because this is the form which crashes:
package com.example.laivumusis;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ViewListData extends AppCompatActivity {
KlausimynoDatabaseHelper myDB;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editlistview_layout);
ListView listView = (ListView) findViewById(R.id.listView);
myDB = new KlausimynoDatabaseHelper(this);
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0) {
Toast.makeText(ViewListData.this,"Database tuščias!",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);
listView.setAdapter(listAdapter);
}
}
}
}
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.laivumusis, PID: 3859
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Your object seems to be null while converting to string. use the following to check if null:
if (obj !=null){
//store in database
}
I want all edit text content that I have saved in SQL to be displayed on the edit bills activity when I click on the list item, but I am only able to retrieve the name and display it again in the intent. Rather than saving another data it should update the record with the new data if I save the existing record another time in the editbills_activity. Here is my DBAdapter.java
package com.example.dhruv.bills;
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 DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "name VARCHAR not null, amount VARCHAR, duedate date );";
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
}
#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 contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
//return db.insert(DATABASE_TABLE, null, initialValues);
// Will return NULL POINTER EXCEPTION as db isn't set
// Replaces commented out line
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public void deleteName(int id, String name){
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "DELETE FROM " + DATABASE_TABLE + " WHERE "
+ KEY_ROWID + " = '" + id + "'" +
" AND " + KEY_NAME + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
{String query1 ="SELECT * FROM" + KEY_TITLE;
Cursor mCursor = db.rawQuery(query1,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}*/
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
// Will return NULL POINTER EXCEPTION as db isn't set
//return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// Replaces commented out line
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}*/
}
Here is my Bills.java (MainActivity)
Problem: Bills.java has the list view that shows the intent whenever the item in list view is clicked, but it does not put the amount and date or update the record. Instead it saves another record.
Solution: I want to retrieve it and display all (name ,amount,duedate) and instead of saving another record it should update it.
package com.example.dhruv.bill;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class bills extends AppCompatActivity {
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mrecycleview =(ListView) findViewById(R.id.mRecycleView);
dbAdapter = new DBAdapter(this);
// mlistview();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab1);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Editbills.class);
startActivity(i);
}
});
mlistview();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void mlistview(){
Log.d(TAG,"mlistview:Display data in listview");
Cursor mCursor = dbAdapter.getAllRecords();
ArrayList<String> listData = new ArrayList<>();
while (mCursor.moveToNext()){
listData.add(mCursor.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = dbAdapter.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(bills.this, Editbills.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
}
}
});
}
}
here is my editbills.java code
package com.example.dhruv.bill;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.editText);
editText2=(EditText)findViewById(R.id.editText2);
editText3 =(EditText)findViewById(R.id.editText3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
editText.setText(selectedName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_Delete) {
db.deleteName(selectedID,selectedName);
editText.setText("");
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
Intent p = new Intent(getApplicationContext(),bills.class);
startActivity(p);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instead of
DBHelper.getWritableDatabase().insert(DATABASE_TABLE, null, initialValues);
in insertRecord function of DBHelper, it should be
DBHelper.getWritableDatabase().update("markers", valores, where, whereArgs);
I have a listView which displays clothing items in my shopping cart from my existing database and at the bottom it shows you the total price of all the items in my cart. When I delete items from my cart, the listView does get updated, it removes the item, but the total price that displays at the bottom does not get updated when I delete this item and this total price just comes from a query that does SUM(Price) from my table which contains my items in my cart. I've posted my some of my code below and if anyone can help, that would be great.
DatabaseHelper.java
package ankitkaushal.app.healthysizing;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DB_PATH = "/data/data/ankitkaushal.app.healthysizing/databases/";
public static String DB_NAME = "AppDatabase";
public static final int DB_VERSION = 1;
public static final String shoppingCartTable = "OPS_insert";
private SQLiteDatabase myDB;
private Context context;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
#Override
public synchronized void close(){
if(myDB!=null){
myDB.close();
}
super.close();
}
// Retrieves all the types of clothing items of the specified brand typed into the search bar
public ArrayList<Item> getAllSearchedItems(String brand, String table_name) {
ArrayList<Item> shirtList = new ArrayList<Item>();
String query = "SELECT * FROM " + table_name + " WHERE Brand LIKE '" + brand + "' ORDER BY Price ASC"; //query to get all the shirts for brand typed in
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
shirtList.add(item);
} while (cursor.moveToNext());
}
return shirtList;
}
// Retrieves all the items of a certain type from the database
public ArrayList<Item> getAllItems(String table_name) {
ArrayList<Item> shirtList = new ArrayList<Item>();
String query = "SELECT * FROM " + table_name + " ORDER BY Price ASC"; //query to get all the shirts
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
shirtList.add(item);
} while (cursor.moveToNext());
}
return shirtList;
}
// Retrieves all the items in the cart
public ArrayList<Item> getItemsInCart() {
ArrayList<Item> cartList = new ArrayList<Item>();
String query = "SELECT * FROM " + shoppingCartTable + " ORDER BY Price ASC"; // query to get all the items in the cart
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setBrand(cursor.getString(0));
item.setStore(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDescription(cursor.getString(3));
item.setSize(cursor.getString(4));
item.setGender(cursor.getString(5));
item.setID(cursor.getString(6));
cartList.add(item);
} while (cursor.moveToNext());
}
return cartList;
}
// Adds the item chosen from the listView to your shopping cart.
public void addToCart(Item item) {
String description = item.getDescription();
description = "\"" + description + "\"";
String query = "INSERT INTO " + shoppingCartTable + " (Brand, Store, Price, Description, Size, Gender, ID) " +
"VALUES ('" + item.getBrand() + "', '" + item.getStore() + "', '" + item.getPrice() + "', "
+ description + ", '" + item.getSize() + "', '" + item.getGender() + "', '" + item.getID() + "')";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
}
// Deletes the item from the shopping cart
public void deleteItemFromCart(String ID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(shoppingCartTable, " ID = '" + ID + "'", null);
}
// Returns total price of items in shopping cart
public String getTotalCartPrice() {
String SQLQuery = "SELECT SUM(Price) FROM OPS_insert";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(SQLQuery, null);
c.moveToFirst();
String priceTotal = c.getString(0);
return priceTotal;
}
public void setLimitSize(String limit, String clothingType) {
String query = "UPDATE clothingLimit SET " + clothingType + " = " + limit;
}
/***
* Open database
* #throws android.database.SQLException
*/
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* Copy database from source code assets to device
* #throws java.io.IOException
*/
public void copyDataBase() throws IOException {
try {
InputStream myInput = context.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e("tle99 - copyDatabase", e.getMessage());
}
}
/***
* Check if the database doesn't exist on device, create new one
* #throws IOException
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e("tle99 - create", e.getMessage());
}
}
}
// ---------------------------------------------
// PRIVATE METHODS
// ---------------------------------------------
/***
* Check if the database is exist on device or not
* #return
*/
private boolean checkDataBase() {
SQLiteDatabase tempDB = null;
try {
String myPath = DB_PATH + DB_NAME;
tempDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
Log.e("tle99 - check", e.getMessage());
}
if (tempDB != null)
tempDB.close();
return tempDB != null ? true : false;
}
}
CartItemsAdapter.java
package ankitkaushal.app.healthysizing;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public final class CartItemsAdapter extends ArrayAdapter<Item> implements View.OnClickListener {
public CartItemsAdapter(Context context, ArrayList<Item> shirtItems) {
super(context, 0, shirtItems);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Item item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.cart_layout, parent, false);
}
// Lookup view for data population
TextView brand = (TextView) convertView.findViewById(R.id.txt_cart_brand);
TextView price = (TextView) convertView.findViewById(R.id.txt_cart_price);
TextView store = (TextView) convertView.findViewById(R.id.txt_cart_store);
TextView size = (TextView) convertView.findViewById(R.id.txt_cart_size);
TextView description = (TextView) convertView.findViewById(R.id.txt_cart_description);
ImageView shirtsImage = (ImageView) convertView.findViewById(R.id.image_view_cart);
Button deleteFromCartButton = (Button) convertView.findViewById(R.id.deleteItemButton);
// Populate the data into the template view using the data object
brand.setText("Brand:" + " " + item.getBrand());
price.setText("Price:" + " $" + item.getPrice());
store.setText("Store:" + " " + item.getStore());
size.setText("Size:" + " " + item.getSize());
description.setText("Description:" + " " + item.getDescription());
Context context = parent.getContext();
try { // Find the image name from database ID column and link that up with the name of image in drawable folder
String itemName = item.getID();
String uri = "#drawable/"+itemName;
int imageResource = context.getResources().getIdentifier(uri, null, context.getApplicationContext().getPackageName());
Drawable drawable = context.getResources().getDrawable(imageResource);
shirtsImage.setImageDrawable(drawable);
}
catch (Exception e) { // If no image found for item, just set the image to a default image in drawable folder
// TODO Auto-generated catch block
Drawable drawable = context.getResources().getDrawable(R.drawable.shirts); // Default image
shirtsImage.setImageDrawable(drawable);
}
deleteFromCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// To get the item from the listView for which the Add to Cart button is pressed
Item item = getItem(position);
// Delete the item from the cart by pressing the delete item button
DatabaseHelper db = new DatabaseHelper(getContext());
db.deleteItemFromCart(item.getID());
remove(item);
// Update the listView to reflect the changes
notifyDataSetChanged();
}
});
// Return the completed view to render on screen
return convertView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
shoppingCart.java
package ankitkaushal.app.healthysizing;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
public class shoppingCart extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
final DatabaseHelper dbhelper;
final ListView listView;
final ListAdapter cartAdapter;
dbhelper = new DatabaseHelper(getApplicationContext());
try {
dbhelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
listView = (ListView) findViewById(R.id.itemsInCartList);
ArrayList<Item> cartList = dbhelper.getItemsInCart();
if (cartList != null) {
cartAdapter = new CartItemsAdapter(getApplicationContext(), cartList);
listView.setAdapter(cartAdapter);
}
listView.setEmptyView(findViewById(R.id.emptyCartMessage));
TextView displayTotalPrice = (TextView) findViewById(R.id.totalCartPrice);
String totalCartPrice = dbhelper.getTotalCartPrice();
if (totalCartPrice != null) {
displayTotalPrice.setText("Total Price: $" + totalCartPrice);
}
else {
displayTotalPrice.setText("Total Price: $0.00");
}
}
}
try to move this from your adapter to YourListView.onItemLongClickListener
from this (in the adapter class)
public void onClick(View arg0) {
// TODO Auto-generated method stub
// To get the item from the listView for which the Add to Cart button is pressed
Item item = getItem(position);
// Delete the item from the cart by pressing the delete item button
DatabaseHelper db = new DatabaseHelper(getContext());
db.deleteItemFromCart(item.getID());
remove(item);
// Update the listView to reflect the changes
notifyDataSetChanged();
}
}
to this (in your activity:
YourListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, final View view, int position, long l) {
// To get the item from the listView for which the Add to Cart button is pressed
Item item = YoutList.get(position);
// Delete the item from the cart by pressing the delete item button
DatabaseHelper db = new DatabaseHelper(getContext());
db.deleteItemFromCart(item.getID());
remove(item);
// Update the listView to reflect the changes
notifyDataSetChanged();
TextView displayTotalPrice = (TextView) findViewById(R.id.totalCartPrice);
String totalCartPrice = dbhelper.getTotalCartPrice();
if (totalCartPrice != null) {
displayTotalPrice.setText("Total Price: $" + totalCartPrice);
}
}
});
I'm building message app and my message and number are showing in list-view but I'm not sure how to pass the list-view data to SQLite database? This is my list view code looks like but not sure how to pass the data to database.
package com.example.sunny.messager;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ListView lv=(ListView)findViewById(R.id.SmsList);
if(fetchInbox()!=null){
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,fetchInbox());
lv.setAdapter(adapter);
}
}
public ArrayList<String> fetchInbox(){
ArrayList<String> sms=new ArrayList<String>();
Uri uriSms=Uri.parse("content://sms/");
Cursor cursor=getContentResolver().query(uriSms, new String[]{"_id","address","date","body"}, null, null, null);
cursor.moveToFirst();
while(cursor.moveToNext()){
String address=cursor.getString(1);
String body=cursor.getString(3);
sms.add("Number: " +address+"\n Message: " +body);
}
return sms;
}
}
You need to use these classes SQLiteDatabase and and SQLiteOpenHelper.
SQLiteDatabase is the class for us to perform CRUD function.
SQLiteOpenHelper is a helper class to manage database creation and version management.
Now let’s start code on table structure portion first – create table in Android. We will create a file name SMSData.java , and the code in this file will look like this
package com.example.sqlitedb;
public class SMSData {
// Labels table name
public static final String TABLE = "SMSData";
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_number = "number";
public static final String KEY_message= "message";
// property help us to keep data
public int SMSData_ID;
public int number;
public String message;
}
We’ll create a class and name it DBHelper.java and code in this file will look like this, to ease on understand code line by line i put comment in code.
package com.example.sqlitedb;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "crud.db";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//All necessary tables you like to create will create here
String CREATE_TABLE_SMSDATA= "CREATE TABLE " + SMSData.TABLE + "("
+ SMSData.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ SMSData.KEY_number+ " INTEGER, "
+ SMSData.KEY_message+ " TEXT )";
db.execSQL(CREATE_TABLE_SMSDATA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone!!!
db.execSQL("DROP TABLE IF EXISTS " + SMSData.TABLE);
// Create tables again
onCreate(db);
}
}
With above 2 steps, SMSData table will be created when app get started and now we could code the CRUD functions! Create SMSDataRepo.java, the purpose of this class is to perform CRUD on the SMSData table. The code in this file will look like this.
package com.example.sqlitedb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.HashMap;
public class SMSDataRepo {
private DBHelper dbHelper;
public SMSDataRepo(Context context) {
dbHelper = new DBHelper(context);
}
public int insert(SMSData sMSData) {
//Open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SMSData.KEY_number, sMSData.number);
values.put(SMSData.KEY_message,sMSData.message);
// Inserting Row
long SMSData_Id = db.insert(SMSData.TABLE, null, values);
db.close(); // Closing database connection
return (int) SMSData_Id;
}
public void delete(int SMSData_Id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// It's a good practice to use parameter ?, instead of concatenate string
db.delete(SMSData.TABLE, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData_Id) });
db.close(); // Closing database connection
}
public void update(SMSData sMSData) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SMSData.KEY_number, sMSData.number);
values.put(SMSData.KEY_message,sMSData.message);
// It's a good practice to use parameter ?, instead of concatenate string
db.update(SMSData.TABLE, values, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData.SMSData_ID) });
db.close(); // Closing database connection
}
public ArrayList<HashMap<String, String>> getSMSDataList() {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
SMSData.KEY_ID + "," +
SMSData.KEY_number+
SMSData.KEY_message+ "," +
" FROM " + SMSData.TABLE;
//SMSData sMSData= new SMSData();
ArrayList<HashMap<String, String>> sMSDataList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> sMSData= new HashMap<String, String>();
sMSData.put("number", cursor.getString(cursor.getColumnIndex(SMSData.KEY_number)));
sMSData.put("message", cursor.getString(cursor.getColumnIndex(SMSData.KEY_message)));
sMSDataList.add(sMSData);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return sMSDataList;
}
public SMSData getSMSDataById(int Id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
SMSData.KEY_ID + "," +
SMSData.KEY_number + "," +
SMSData.KEY_message +
" FROM " + SMSData.TABLE
+ " WHERE " +
SMSData.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string
int iCount =0;
SMSData sMSData= new SMSData();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );
if (cursor.moveToFirst()) {
do {
sMSData.SMSData_ID =cursor.getInt(cursor.getColumnIndex(SMSData.KEY_ID));
sMSData.number=cursor.getInt(cursor.getColumnIndex(SMSData.KEY_number));
sMSData.message=cursor.getString(cursor.getColumnIndex(SMSData.KEY_message));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return sMSData;
}
}
I'm currently having trouble deleting one row when user long presses on an item in listview. I am able to only delete one row at a time which is what I want, but when I delete the first few items it is successful and when I attempt to delete an item with a later id. The id does not get deleted and stays. I need help to consistently delete items when ever an item is to be deleted. Thanks.
this is my database helper class
package com.example.health.adapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.health.dao.ExerciseDAO;
import com.example.health.dao.RecipeDAO;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "HealthDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE recipe ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, " +
"description TEXT )";
db.execSQL(CREATE_RECIPE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS recipe");
this.onCreate(db);
}
//START OF CRUD FOR RECIPE
private static final String TABLE_RECIPE = "recipe";
//column names
private static final String KEY_RID = "id";
private static final String KEY_RTITLE = "title";
private static final String KEY_RDESCRIPTION = "description";
private static final String[] RCOLUMNS = {KEY_RID,KEY_RTITLE,KEY_RDESCRIPTION};
public void addRecipe(RecipeDAO r) {
Log.d("addRecipe", r.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RTITLE, r.getTitle());
values.put(KEY_RDESCRIPTION, r.getDescription());
db.insert(TABLE_RECIPE, null, values);
Log.d("Data Added", r.toString());
db.close();
}
public RecipeDAO getRecipe(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(TABLE_RECIPE, // a. table
RCOLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null);
if (cursor != null)
cursor.moveToFirst();
RecipeDAO r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
Log.d("getRecipe("+id+")", r.toString());
return r;
}
public List<RecipeDAO> getAllRecipe() {
List<RecipeDAO> recipe = new ArrayList<RecipeDAO>();
String query = "SELECT * FROM " + TABLE_RECIPE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
RecipeDAO r = null;
if (cursor.moveToFirst()) {
do {
r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
recipe.add(r);
} while (cursor.moveToNext());
}
Log.d("getAllRecipe()", recipe.toString());
return recipe;
}
public int updateRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", r.getTitle());
values.put("description", r.getDescription());
int i = db.update(TABLE_RECIPE, //table
values, // column/value
KEY_RID+" = ?", // selections
new String[] { String.valueOf(r.getRecipeID()) });
db.close();
return i;
}
public void deleteAllRecipe() {
RecipeDAO r = new RecipeDAO();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE,null,null);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_RECIPE + "'");
db.close();
Log.d("deleteRecipe", r.toString());
}
/*
public void deleteRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE, KEY_RID+ " = ? ", new String[] { String.valueOf(r.getRecipeID()) });
db.close();
}*/
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + "=" + id, null) > 0;
}
//END OF CRUD FOR RECIPE
}
Class for database CRUD operations
package com.example.health.recipe;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.health.adapter.MySQLiteHelper;
import com.example.health.dao.RecipeDAO;
import com.example.health.healthplanner.R;
import java.util.List;
public class Recipes extends Fragment {
MySQLiteHelper db;
Button deleteButton;
ListView lv;
List<RecipeDAO> data;
RecipeDAO r = new RecipeDAO();
public Recipes() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.recipe_fragment, container, false);
db = new MySQLiteHelper(getActivity());
/*
db.addRecipe(new RecipeDAO("Windows", "Bill Gates"));//hardcode test
db.addRecipe(new RecipeDAO("IOS", "Steve Jobs"));//same
db.addRecipe(new RecipeDAO("Android", "Andy Rubin"));//same*/
data = db.getAllRecipe();
final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, data);
lv = (ListView) v.findViewById(R.id.listView2);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
deleteButton = (Button) v.findViewById(R.id.deletebutton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete");
alertDialog.setMessage("Are you sure you want to delete all data?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.deleteAllRecipe();
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "All data delete", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.show();
/* data = db.getAllRecipe();
for(RecipeDAO re : data) { testing to see if data is in database
String log = "Id: " + re.getRecipeID() + ", Title: " + re.getTitle();
Log.d("Data", log);
}*/
}
});
return v;
}
}
try this
public void delete(String name) {
db.delete(your_table_name, "name= ?", new String[] { name });
}
Please revise this method,
//change code in setOnItemLongClickListener
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
data = db.getAllRecipe();
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, data);
//and call change adapter in listview
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
//this method for delete in sqlite database
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + " =?" , new String[]{id}) > 0;
}