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;
}
Related
I am trying to implement a search function into a custom list view. I using a menu for the search feature. When I type into the search bar, my project crashes with this error.
2019-11-19 18:50:05.762 17072-17072/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.medicationmanagementsystem, PID: 17072
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object
reference
at com.example.medicationmanagementsystem.ViewListContents$1.onQueryTextChange(ViewListContents.java:72)
I think it is getting null for the array and is therefore unable to show any details. Any help would be grateful.
ViewListContents.java
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuItemCompat;
import com.example.medicationmanagementsystem.DAO.DatabaseHelper;
import java.util.ArrayList;
public class ViewListContents extends AppCompatActivity {
DatabaseHelper myDB;
ArrayList<Prescription> prescriptionList;
ListView listView;
Prescription prescription;
ArrayList<String> listItem;
ArrayAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcontents_layout);
myDB = new DatabaseHelper(this);
prescriptionList = new ArrayList<Prescription>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(ViewListContents.this, "There is nothing in this database", Toast.LENGTH_LONG).show();
}
else {
while(data.moveToNext()){
prescription = new Prescription(data.getString(1), data.getString(2), data.getString(3),
data.getString(4), data.getString(5), data.getString(6), data.getString(7),
data.getString(8), data.getString(9));
prescriptionList.add(prescription);
}
EightColumn_ListAdapter adapter = new EightColumn_ListAdapter(this,R.layout.prescription_view,prescriptionList);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
}
//END
//This code is based on SQLite Database to ListView- Part 4:Search Items- Android Studio Tutorial, KOD Dev, https://www.youtube.com/watch?v=QY-O49a_Ags
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<String> listViews = new ArrayList<>();
for (String prescription : listItem){
if (prescription.toLowerCase().contains(newText.toLowerCase())){
listViews.add(prescription);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ViewListContents.this,R.layout.prescription_view,listViews);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
}
DatabaseHelper.java
package com.example.medicationmanagementsystem.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
//Create Database
public static final String DATABASE_NAME = "ManagementSystem.db";
//Create patient table
public static final String TABLE_PATIENT = "patient_table";
public static final String COL_PATIENT_PATIENTID = "PATIENTID";
public static final String COL_PATIENT_FNAME = "FNAME";
public static final String COL_PATIENT_SNAME = "SNAME";
public static final String COL_PATIENT_PPS = "PPS";
public static final String COL_PATIENT_DOB = "DOB";
public static final String COL_PATIENT_ADDRESS = "ADDRESS";
public static final String COL_PATIENT_TYPE = "PATIENTTYPE";
public static final String COL_PATIENT_MEDCOND = "PATIENTMEDCON";
public static final String COL_PATIENT_CARINGID = "CARINGID";
//Create prescription table
public static final String TABLE_PRESCRIPTION = "prescription_table";
public static final String COL_PRESCRIPTION_ID = "PRESCRIPTIONID";
public static final String COL_PRESCRIPTION__PATIENTID = COL_PATIENT_PATIENTID;
public static final String COL_PRESCRIPTION__DATE = "DATE";
public static final String COL_PRESCRIPTION__DRUGNAME = "DRUGNAME";
public static final String COL_PRESCRIPTION__CONCENTRATION = "CONCENTRATION";
public static final String COL_PRESCRIPTION__DOSAGE = "DOSAGE";
public static final String COL_PRESCRIPTION__PREPARATION = "PREPARATION";
public static final String COL_PRESCRIPTION__STARTDATE = "STARTDATE";
public static final String COL_PRESCRIPTION__ENDDATE = "ENDDATE";
public static final String COL_PRESCRIPTION__DOCTORID = "DOCTORID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATIENTID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PATIENT);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PRESCRIPTION);
onCreate(db);
}
//insert patient data
public boolean insertPatientData(String fname, String sname, String pps, String dob, String address, String patienttype, String patientmedcon, String caringid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL_PATIENT_FNAME, fname);
contentValues1.put(COL_PATIENT_SNAME, sname);
contentValues1.put(COL_PATIENT_PPS, pps);
contentValues1.put(COL_PATIENT_DOB, dob);
contentValues1.put(COL_PATIENT_ADDRESS, address);
contentValues1.put(COL_PATIENT_TYPE, patienttype);
contentValues1.put(COL_PATIENT_MEDCOND,patientmedcon);
contentValues1.put(COL_PATIENT_CARINGID, caringid);
long result= db.insert(TABLE_PATIENT,null, contentValues1);
if (result == 1)
return false;
else
return true;
}
//insert prescription data
public boolean insertData(String patientid, String date, String drugname, String concentration,String dosage, String preparation, String startdate, String enddate, String doctorid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_PRESCRIPTION__PATIENTID, patientid);
contentValues2.put(COL_PRESCRIPTION__DATE, date);
contentValues2.put(COL_PRESCRIPTION__DRUGNAME, drugname);
contentValues2.put(COL_PRESCRIPTION__CONCENTRATION, concentration);
contentValues2.put(COL_PRESCRIPTION__DOSAGE, dosage);
contentValues2.put(COL_PRESCRIPTION__PREPARATION, preparation);
contentValues2.put(COL_PRESCRIPTION__STARTDATE, startdate);
contentValues2.put(COL_PRESCRIPTION__ENDDATE, enddate);
contentValues2.put(COL_PRESCRIPTION__DOCTORID, doctorid);
long result= db.insert(TABLE_PRESCRIPTION,null, contentValues2);
if (result == 1)
return false;
else
return true;
//END
}
//Coding with mitch tutorial
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_PRESCRIPTION, null);
return data;
}
////This code is based on SQLite Database to ListView- Part 4:Search Items- Android Studio Tutorial, KOD Dev, https://www.youtube.com/watch?v=QY-O49a_Ags
public Cursor searchPrescriptions(String text) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * from " + TABLE_PRESCRIPTION + "WHERE " + COL_PRESCRIPTION__PATIENTID + " Like '%" + text +"%'";
Cursor data = db.rawQuery(query, null);
return data;
}
}
Eight_Column_ListAdapter.java
package com.example.medicationmanagementsystem;
//The code below is based on Adding multiple columns to your ListView, CodingWithMitch, https://www.youtube.com/watch?v=8K-6gdTlGEA, https://www.youtube.com/watch?v=hHQqFGpod14, https://www.youtube.com/watch?v=jpt3Md9aDIQ
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class EightColumn_ListAdapter extends ArrayAdapter<Prescription> {
private LayoutInflater mInflater;
private ArrayList<Prescription> prescriptions;
private int mViewResourceId;
public EightColumn_ListAdapter(Context context, int textViewResourceId, ArrayList<Prescription> prescriptions) {
super(context, textViewResourceId, prescriptions);
this.prescriptions = prescriptions;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents) {
convertView = mInflater.inflate(mViewResourceId, null);
Prescription prescription = prescriptions.get(position);
if (prescription != null) {
TextView patientID = (TextView) convertView.findViewById(R.id.textpatientID);
TextView date = (TextView) convertView.findViewById(R.id.textdate);
TextView drugname = (TextView) convertView.findViewById(R.id.textdrugname);
TextView concentration = (TextView) convertView.findViewById(R.id.textcontentration);
TextView dosage = (TextView) convertView.findViewById(R.id.textdosage);
TextView prep = (TextView) convertView.findViewById(R.id.textprep);
TextView startdate = (TextView) convertView.findViewById(R.id.textstartdate);
TextView enddate = (TextView) convertView.findViewById(R.id.textenddate);
TextView doctorID = (TextView) convertView.findViewById(R.id.textdoctorid);
if(patientID != null) {
patientID.setText((prescription.getPatientID()));
}
if(date != null) {
date.setText((prescription.getPresdate()));
}
if(drugname != null) {
drugname.setText((prescription.getDrugname()));
}
if(concentration != null) {
concentration.setText((prescription.getConcentration()));
}
if(dosage != null) {
dosage.setText((prescription.getDosage()));
}
if(prep != null) {
prep.setText((prescription.getPreparation()));
}
if(startdate != null) {
startdate.setText((prescription.getStartdate()));
}
if(enddate != null) {
enddate.setText((prescription.getEnddate()));
}
if(doctorID != null) {
patientID.setText((prescription.getDoctorID()));
}
}
return convertView;
}
}
You are trying to read the elements of your list called listItem . That list is null because you never set it to anything else.
Change this:
ArrayList<String> listItem;
to this:
ArrayList<String> listItem = new ArrayList<String>();
... or you can put it in your onCreate() method, just as you did with prescriptionList :
prescriptionList = new ArrayList<Prescription>();
listItem = new ArrayList<String>();
Also, don't name your list listItem because it is not an item... it is a list!
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'm developing a contacts app with a photo. I have Store and retrieve data from SQLite and it's working fine on my list view.
The problem is when I click a list item from it's supposed to show an image view and few other details. but the image is not showing on the Activity
List View on Main Activity
In the empty space here should be an image of the contacts
UserDBHelper.java
package com.example.arif.contacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
public class UserDBHelper extends SQLiteOpenHelper {
String TAG = "DEBUG";
private static final String DATABASE_NAME = "USERINFO.DB";
private static final String TABLE_NAME = "ContactTable";
private static final String TABLE_COL_NAME = "NAME";
private static final String TABLE_COL_MOB = "MOB";
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
private static final String TABLE_COL_ID = "ID";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+TABLE_NAME+"("+TABLE_COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TABLE_COL_NAME+" TEXT, "+TABLE_COL_MOB+" TEXT, "+TABLE_COL_EMAIL+" TEXT, "+TABLE_COL_IMG+" blob)" ;
public UserDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DataBase", "Database created / Opened");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DataBase", "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public boolean AddInfo(String Name, String Mob , String Email, byte[] img )
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put("NAME", Name);
CV.put("MOB", Mob);
CV.put("EMAIL", Email );
CV.put("NewImage", img);
long result = db.insert(TABLE_NAME, null,CV);
Log.e("DataBase", "Add Info Bug");
if(result == -1)
{
return false;
}
else
{
return true;
}
}
public Cursor getInformation()
{
Cursor data;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select * from " + TABLE_NAME;
data = db.rawQuery(query,null);
return data;
}
public String fetch_Name(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_NAME+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_NAME+""));
}
return Str;
}
public String fetch_MOB(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_MOB+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_MOB+""));
}
return Str;
}
public String fetch_Email(int i)
{
String Str = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select "+TABLE_COL_EMAIL+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
Str = data.getString(data.getColumnIndex(TABLE_COL_EMAIL+""));
}
return Str;
}
public Bitmap fetch_Img(int i) { /// THIS FUNCTION IS NOT WORKING
byte[] ImgByte;
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select "+TABLE_COL_IMG+" FROM " + TABLE_NAME + " WHERE " +TABLE_COL_ID+" = "+i;
Cursor data = db.rawQuery(query,null);
if(data.moveToFirst())
{
ImgByte = data.getBlob(data.getColumnIndex(TABLE_COL_IMG+""));
Bitmap bitMAP = BitmapFactory.decodeByteArray(ImgByte, 0, ImgByte.length); // Here it's Always Returning Null
if(bitMAP == null)
{
Log.e( TAG, "Bitmap is null :/ ");
}
return bitMAP;
}
return null;
}
}
DetailsViewActivity
package com.example.arif.contacts;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class DetailsOfContacts extends AppCompatActivity {
int Pos;
TextView Name_View, Mob_View, Email_View;
ImageView Image_View;
UserDBHelper userDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_of_contacts);
//---- ---- Intend Bundle ---- ----
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Pos = -1;
if(bundle != null)
{
Pos = bundle.getInt("Position");
}
Toast.makeText(getApplicationContext(), "Position "+ Pos,Toast.LENGTH_SHORT).show();
// ---- ---- Find View ---- ----
Name_View = (TextView) findViewById(R.id.DetName);
Mob_View = (TextView) findViewById(R.id.DetMob);
Email_View = (TextView) findViewById(R.id.DetEmail);
Image_View = (ImageView) findViewById(R.id.DetImg);
/// --- --- DataBase -----
UserDBHelper userDBHelper = new UserDBHelper(getApplicationContext());
Name_View.setText(userDBHelper.fetch_Name(Pos+1)); // Working Fine
Mob_View.setText(userDBHelper.fetch_MOB(Pos+1));// Working Fine
Email_View.setText(userDBHelper.fetch_Email(Pos+1));// Working Fine
Image_View.setImageBitmap(userDBHelper.fetch_Img(Pos+1)); // it's Not showing The image in activity
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id ;
id = item.getItemId();
if(id == R.id.EditButt)
{
Toast.makeText(getApplicationContext(),"Edit Button Clicked", Toast.LENGTH_SHORT).show();
Intent I = new Intent(DetailsOfContacts.this, EditActivity.class);
startActivity(I);
return true;
}
return super.onOptionsItemSelected(item);
}
}
09-18 09:35:56.866 26144-26144/com.example.arif.contacts E/DEBUG: Bitmap is null :/
Column name of image and email are same
private static final String TABLE_COL_EMAIL = "EMAIL";
private static final String TABLE_COL_IMG = "EMAIL";
Change column name of image.
No matter how many times I've reviewed my code I keep getting a LogCat error of
Process: com.zito.zitolab4, PID: 2357
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zito.zitolab4/com.zito.zitolab4.ZitoLab4Data}: android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT id, title, genre, releaseYear FROM movies
Based on the LogCat I figured it would be in the Data.Java Class but I've looked everywhere and I'm just not setting it.I would appreciate any advice.
Thanks
Data.Java
package com.zito.zitolab4;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class ZitoLab4Data extends ActionBarActivity {
TextView idView;
EditText titleBox, genreBox, yearBox;
Button addMovieButton;
TableLayout movieTable;
private ZitoDataController sqlCon;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zito_lab4_data);
sqlCon = new ZitoDataController(this);
titleBox = (EditText) findViewById(R.id.movieTitle);
genreBox = (EditText) findViewById(R.id.movieGenre);
yearBox = (EditText) findViewById(R.id.releaseYear);
addMovieButton = (Button) findViewById(R.id.addMovieButton);
movieTable = (TableLayout) findViewById(R.id.movieTable);
BuildTable();
addMovieButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new MyAsync().execute();
}
});
}
#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_zito_lab4_data, 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 BuildTable() {
sqlCon.open();
Cursor dbCursor = sqlCon.readEntry();
int movies = dbCursor.getCount();
int fields = dbCursor.getColumnCount();
// 1 row for each person in the database table
for (int i = 0; i < movies; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
// create a TextView for each field in the record
for (int j = 0; j < fields; j++) {
TextView TableDataTextView = new TextView(this);
TableDataTextView.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
TableDataTextView.setTextSize(16);
TableDataTextView.setPadding(0, 5, 0, 5);
TableDataTextView.setText(dbCursor.getString(j));
row.addView(TableDataTextView);
}
dbCursor.moveToNext();
movieTable.addView(row);
}
sqlCon.close();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
movieTable.removeAllViews();
progressDialog = new ProgressDialog(ZitoLab4Data.this);
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String title = titleBox.getText().toString();
String genre = genreBox.getText().toString();
int year = Integer.parseInt(yearBox.getText().toString());
sqlCon.open();
sqlCon.insertData(title, genre, year);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
BuildTable();
progressDialog.dismiss();
titleBox.setText("");
genreBox.setText("");
yearBox.setText("");
titleBox.requestFocus();
}
}
}
DataModel.Java
package com.zito.zitolab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ZitoDataModel extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ZitoLab4DB.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_MOVIES = "movies";
public static final String MOVIE_ID = "id";
public static final String MOVIE_TITLE = "title";
public static final String MOVIE_GENRE = "genre";
public static final String MOVIE_YEAR = "releaseYear";
public ZitoDataModel(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_MOVIES + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," +
MOVIE_TITLE + " TEXT," + MOVIE_GENRE + " STRING, " + MOVIE_YEAR + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES);
onCreate(db);
}
public void addMovie(String title, String genre, int year) {
ContentValues values = new ContentValues();
values.put(MOVIE_TITLE, title);
values.put(MOVIE_GENRE, genre);
values.put(MOVIE_YEAR, year);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_MOVIES, null, values);
db.close();
}
public Cursor readEntry(){
SQLiteDatabase db = this.getWritableDatabase();
String[] allColumns = new String[]{ZitoDataModel.MOVIE_ID, ZitoDataModel.MOVIE_TITLE,
ZitoDataModel.MOVIE_GENRE, ZitoDataModel.MOVIE_YEAR};
Cursor dbCursor = db.query(ZitoDataModel.TABLE_MOVIES, allColumns,
null, null, null, null, null);
if (dbCursor !=null) {
dbCursor.moveToFirst();
}
return dbCursor;
}
}
DataController.Java
package com.zito.zitolab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ZitoDataController {
private ZitoDataModel dataModel;
private Context movieContext;
private SQLiteDatabase database;
public ZitoDataController(Context context) {
movieContext = context;
}
public ZitoDataController open() throws SQLException {
dataModel = new ZitoDataModel(movieContext);
database = dataModel.getWritableDatabase();
return this;
}
public void close()
{
dataModel.close();
}
public void insertData(String title, String genre, int year) {
ContentValues values = new ContentValues();
values.put(ZitoDataModel.MOVIE_TITLE, title);
values.put(ZitoDataModel.MOVIE_GENRE, genre);
values.put(ZitoDataModel.MOVIE_YEAR, year);
database.insert(ZitoDataModel.TABLE_MOVIES, null, values);
}
public Cursor readEntry() {
String[] allColumns = new String[]{ZitoDataModel.MOVIE_ID, ZitoDataModel.MOVIE_TITLE,
ZitoDataModel.MOVIE_GENRE, ZitoDataModel.MOVIE_YEAR};
Cursor dataCursor = database.query(ZitoDataModel.TABLE_MOVIES,
allColumns, null, null, null, null, null);
if (dataCursor != null) {
dataCursor.moveToFirst();
}
return dataCursor;
}
}
You possibly modified the table in a later moment (after the very first run).
Uninstall and reinstall your app.
Or, alternatively, increase the value of this constant: DATABASE_VERSION
In the first case, the database will be created normally (for the first time).
The second case causes the onUpgrade() method to fire which will in turn call
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES);
onCreate(db);
So, de facto, deleting the existing table and then re-creating it.
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);
}
}
});
}