This is my MainActivity.
public class MainActivity extends Activity {
EditText etName, etEmail;
DatabaseHelper dbHelper;
Button save;
// declare view
ListView lvEmployees;
// declare adapter
CustomizedAdapter adapter;
// datasource
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
save = (Button) findViewById(R.id.btnSave);
lvEmployees = (ListView) findViewById(R.id.lvEmployees);
dbHelper = new DatabaseHelper(this);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
save(v);
}
});
}
public void save(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
Employee employee = new Employee(name, email);
Toast.makeText(getApplicationContext(), employee.toString(),
Toast.LENGTH_LONG).show();
long inserted = dbHelper.insertEmployee(employee);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "Data inserted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Data insertion failed...",
Toast.LENGTH_LONG).show();
}
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
}
}
This is my DataBaseHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "task_management";
public static final int DB_VERSION = 1;
public static final String EMPLOYEE_TABLE = "employee";
public static final String ID_FIELD = "_id";
public static final String NAME_FIELD = "name";
public static final String EMAIL_FIELD = "email";
public static final String EMPLOYEE_TABLE_SQL = "CREATE TABLE "
+ EMPLOYEE_TABLE + " (" + ID_FIELD + " INTEGER PRIMARY KEY, "
+ NAME_FIELD + " TEXT, " + EMAIL_FIELD + " DATETIME);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create tables
db.execSQL(EMPLOYEE_TABLE_SQL);
Log.e("TABLE CREATE", EMPLOYEE_TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// upgrade logic
}
// insert
public long insertEmployee(Employee emp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_FIELD, emp.getName());
values.put(EMAIL_FIELD, emp.getEmail());
long inserted = db.insert(EMPLOYEE_TABLE, null, values);
db.close();
return inserted;
}
// query
public ArrayList<Employee> getAllEmployees() {
ArrayList<Employee> allEmployees = new ArrayList<Employee>();
SQLiteDatabase db = this.getReadableDatabase();
// String[] columns={NAME_FIELD, EMAIL_FIELD, PHONE_FIELD};
// SELECT * FROM EMPLOYEE;
Cursor cursor = db.query(EMPLOYEE_TABLE, null, null, null, null, null,
null);
// Cursor cursor = db.rawQuery("SELECT * FROM EMPLOYEE", null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
//
int id = cursor.getInt(cursor.getColumnIndex(ID_FIELD));
String name = cursor.getString(cursor
.getColumnIndex(NAME_FIELD));
String email = cursor.getString(cursor
.getColumnIndex(EMAIL_FIELD));
Employee e = new Employee(id, name, email);
allEmployees.add(e);
cursor.moveToNext();
}
}
cursor.close();
db.close();
return allEmployees;
}
}
When i put data and pressed the save button then my data is saved and show in my ListView.
But when i close the apps and open it then i don't see any data in my ListView.
After putting data and pressed save button my new and existing data show in my ListView.
So how can i show my existing data in ListView after open my apps and without press the save button.
If you want to show data each time app starts, you would need to move your list populating code in onCreate
Move this code to onCreate instead of Save button's onClick
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
Hope it helps.
P.S: If you need to repopulate list after Save button's click, make a separate function which contains this code. And call tha function in onCreate as well as in Save button's onClick
You are setting the adapter for the list view in your save method that is called only when you actually press the save button. Here's the part where you do it.
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
Thats why there is no data in the listview when you open the app.
You should do this in your onCreate method, and in your save you should do something like this:
1. declare the the arraylist of employees along with listview;
ArrayList<Employee> employees;
in your oncreate call this code that you should remove from the save method
employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
in save method just add one more item to the list, and notify adapter that there has been a change in the data it's displaying.
employees.add(employee);
adapter.notifyDataSetChanged();
Related
I am working on android application I which I am using Recycler Adapter and Sqlite database to delete and update the sqlite database.
My Problem is when I Click on Item in Recycler view to delete It Deletes the data from list, But When I Click Back and open List Again The deleted data is still there.
I have checked my database From device File Explorer That The Data does not deleted from database.
Same thing happens with the Update
Here is My Recycler Adapter Class
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {
private List<User> listUsers;
Context mContext;
RecyclerView mRecyclerView;
ItemClickListenerLongPressed itemClickListenerLongPressed;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
View itemView;
public UserRecyclerAdapterSavedUsers(List<User> listUsers,RecyclerView recyclerView) {
this.listUsers = listUsers;
mRecyclerView=recyclerView;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext= parent.getContext();
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_second, parent, false);
return new UserViewHolder(itemView);
}
/**
* ViewHolder class
*/
public class UserViewHolder extends RecyclerView.ViewHolder {
//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
LinearLayout layout;
public UserViewHolder(View view) {
super(view);
textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
layout = (LinearLayout) view.findViewById(R.id.list_view);
}
}
#Override
public void onBindViewHolder(UserViewHolder holder, final int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());
holder.layout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
displayingAlertDialog(position);
return false;
}
});
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed) {
this.itemClickListenerLongPressed = itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+listUsers.size());
return listUsers.size();
}
private void displayingAlertDialog(final int position) {
final User user= new User();
//displaying alert dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setTitle("Choose Option");
builder.setMessage("Update or Delete?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
gotupdateuserActivity(user.getUserid());
// dialog.cancel();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to Remove Item
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deletePersonRecord(user.getUserid(), mContext);
listUsers.remove( position);
notifyItemRemoved(position);
mRecyclerView.removeViewAt(position);
notifyItemRangeChanged(position, listUsers.size());
notifyDataSetChanged();
dialog.cancel();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
public void remove(int position) {
listUsers.remove(position);
notifyItemRemoved(position);
}
private void gotupdateuserActivity(String userid) {
Intent goToUpdate = new Intent(mContext, UpdateUserRec.class);
goToUpdate.putExtra("USER_ID", userid);
Toast.makeText(mContext, "USER REC", Toast.LENGTH_SHORT).show();
mContext.startActivity(goToUpdate);
}
}
Here is Sqlite Database Helper Class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 2;
Context context;
// Database Name
private static final String DATABASE_NAME = "DynamicERP.db";
public static final String table_imei = "IMEITABLE";
public static final String table_login= "USERLOGIN";
// User Table Columns names
public static final String imeiid = "IMEIID";
public static final String imei = "IMEI";
public static final String userid = "USERID";
public static final String username = "USERNAME";
public static final String password = "PASSWORD";
public static final String userrole = "USERROLE";
// create table sql query
private static final String DATABASE_CIMEI = "CREATE TABLE " + table_imei + "("
+ imeiid + " INTEGER, " + imei + " VARCHAR );" ;
private static final String DATABASE_CUSER = "CREATE TABLE " + table_login + "("
+ userid + " INTEGER, " + username + " VARCHAR, " + password + " INTEGER, " + userrole + " VARCHAR );" ;
// drop table sql query
private String DROP_IMEI_TABLE = "DROP TABLE IF EXISTS " + table_imei;
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + table_login;
/**
* Constructor
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CIMEI);
db.execSQL(DATABASE_CUSER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
/**
* This method is to create user record
*
* #param user
*/
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(userid,user.getUserid());
values.put(username, user.getName());
values.put(password, user.getPassword());
values.put(userrole, user.getRole());
// Inserting Row
db.insert(table_login, null, values);
db.close();
}
public void addIMEI(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(imei,user.getImei());
values.put(imeiid, user.getImeiid());
// Inserting Row
db.insert(table_imei, null, values);
db.close();
}
/**
* This method is to fetch all user and return the list of user records
*
* #return list
*/
public List<User> getAllUser() {
// array of columns to fetch
String[] columns = {
userid,
username,
password,
userrole
};
// sorting orders
String sortOrder =
userid + " ASC";
List<User> userList = new ArrayList<User>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
User user = new User();
//user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(userid))));
user.setUserid(cursor.getString(cursor.getColumnIndex(userid)));
user.setName(cursor.getString(cursor.getColumnIndex(username)));
user.setPassword(cursor.getString(cursor.getColumnIndex(password)));
user.setRole(cursor.getString(cursor.getColumnIndex(userrole)));
// Adding user record to list
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
/**
* This method is to fetch all user and return the list of user records
*
* #return list
*/
public List<User> getAllImei() {
// array of columns to fetch
String[] columns = {
imeiid,
imei,
};
// sorting orders
String sortOrder =
imeiid + " ASC";
List<User> userList = new ArrayList<User>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(table_imei, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
User user = new User();
//user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(userid))));
user.setImei(cursor.getString(cursor.getColumnIndex(imei)));
user.setImeiid(cursor.getString(cursor.getColumnIndex(imeiid)));
// Adding user record to list
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
/**
* This method to update user record
*
* #param receivedUSERId
* #param updateUserRec
* #param user
*/
public void updateUser(String receivedUSERId, UpdateUserRec updateUserRec, User user) {
SQLiteDatabase db = this.getWritableDatabase();
String strSQL = "UPDATE "+table_login+ " SET "+username+" = "+user.getName()+"," +
" "+password+" = "+user.getPassword()+","+userrole+" = "+user.getRole()+"" +
" WHERE "+userid+" = "+receivedUSERId;
db.execSQL(strSQL);
db.close();
}
/**
* This method is to delete user record
*
* #param user
*/
public void deleteUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(table_login, userid + " = ?",
new String[]{String.valueOf(user.getUserid())});
db.close();
}
/**
* This method to check user exist or not
*
#param userid
* #return true/false
*/
public boolean checkUser(String userid) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?";
// selection argument
String[] selectionArgs = {userid};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE imei = 'dynamic#imei.com';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to check user exist or not
*
* #param email
* #param password
* #return true/false
*/
public boolean checkUser(String email, String password) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?" + " AND " + password + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack#androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to check user exist or not
*
* #param userid
* #param username
* #return true/false
*/
public boolean checkUserData(String userid, String username) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?" + " AND " + username + " = ?";
// selection arguments
String[] selectionArgs = {userid, username};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack#androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public boolean checkUserData(String userid) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?";
// selection argument
String[] selectionArgs = {userid};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'dynamic#data.com';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public User getUser(String id){
SQLiteDatabase db = this.getWritableDatabase();
String query= "SELECT * FROM "+table_login;
Cursor cursor = db.rawQuery(query, null);
User user = new User();
if(cursor.getCount() > 0) {
cursor.moveToFirst();
user.setUserid(cursor.getString(cursor.getColumnIndex(userid)));
user.setName(cursor.getString(cursor.getColumnIndex(username)));
user.setPassword(cursor.getString(cursor.getColumnIndex(password)));
user.setRole(cursor.getString(cursor.getColumnIndex(userrole)));
}
return user;
}
public void deletePersonRecord(String useridValue, Context mContext) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table_login+" WHERE "+userid +"='"+useridValue+"'");
Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show();
db.close();
}
public void deleteIMEIRecord(String imeiidValue, Context mContext) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table_imei+" WHERE "+imeiid +"='"+imeiidValue+"'");
Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show();
}
public void updateIMEI(String receivedIMEIId, UpdateIMEIRec updateIMEIRec, User user) {
SQLiteDatabase db = this.getWritableDatabase();
String strSQL = "UPDATE "+table_imei+ " SET "+imei+" = "+user.getImei()+"," +
" "+imeiid+" = "+user.getImeiid()+
" WHERE "+imeiid+" = "+receivedIMEIId;
db.execSQL(strSQL);
db.close();
}
public User getIMEI(String receivedIMEIId) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + table_imei ;
Cursor cursor = db.rawQuery(query, null);
User user = new User();
if(cursor.getCount() > 0) {
cursor.moveToFirst();
user.setImeiid(cursor.getString(cursor.getColumnIndex(imeiid)));
user.setImei(cursor.getString(cursor.getColumnIndex(imei)));
}
return user;
}
}
And Here is my Recycler List Activity Class
public class UserUpdateListActivity extends AppCompatActivity {
AppCompatActivity activity = UserUpdateListActivity.this;
AppCompatTextView textViewName;
RecyclerView recyclerViewUsers;
AppCompatButton textViewButtonNewUser;
List<User> listUsers;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_record_updated_list);
//getSupportActionBar().setTitle("");
initViews();
initObjects();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(UserUpdateListActivity.this,AdminMain.class));
finish();
}
#Override
protected void onRestart() {
super.onRestart();
}
/**
* This method is to initialize views
*/
private void initViews() {
textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
textViewButtonNewUser = (AppCompatButton) findViewById(R.id.btnaddnew);
recyclerViewUsers = (RecyclerView) findViewById(R.id.recyclerViewUsers);
textViewButtonNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UserUpdateListActivity.this,UserRecordSaveActivity.class));
}
});
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listUsers = new ArrayList<>();
userRecyclerAdapterSavedUsers = new UserRecyclerAdapterSavedUsers(listUsers,recyclerViewUsers);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewUsers.setLayoutManager(mLayoutManager);
recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
recyclerViewUsers.setHasFixedSize(true);
recyclerViewUsers.setAdapter(userRecyclerAdapterSavedUsers);
databaseHelper = new DatabaseHelper(activity);
String emailFromIntent = getIntent().getStringExtra("USERS");
textViewName.setText(emailFromIntent);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listUsers.clear();
listUsers.addAll(databaseHelper.getAllUser());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
userRecyclerAdapterSavedUsers.notifyDataSetChanged();
}
}.execute();
}
}
This is the Query I am using to delete the data
public void deletePersonRecord(String useridValue, Context mContext) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table_login+" WHERE "+userid +"='"+useridValue+"'");
Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show();
db.close();
}
Here is image of my recycler list
List Items
As I click on an Item It open me a Dialog like this
Dialog
When I click on delete this shows me this
Clicking on Delete
After that As I pressed back and again open the Data I deleted again open
Logcat has no Errors
Here is my update activity
public class UpdateUserRec extends AppCompatActivity {
EditText UserIDUpdate,UserNameUpdate,UserPasswordUpdate,UserRoleUpdate;
Button BtnUserRecUpdate;
DatabaseHelper dbHelper;
String receivedUSERId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_record);
UserIDUpdate= (EditText) findViewById(R.id.useridupdate);
UserNameUpdate= (EditText) findViewById(R.id.usernameupdate);
UserPasswordUpdate= (EditText) findViewById(R.id.userpasswordupdate);
UserRoleUpdate= (EditText) findViewById(R.id.userroleupdate);
BtnUserRecUpdate= (Button) findViewById(R.id.userbtnupdate);
dbHelper = new DatabaseHelper(this);
try {
//get intent to get person id
receivedUSERId= getIntent().getStringExtra("USER_ID");
} catch (Exception e) {
e.printStackTrace();
}
User user= dbHelper.getUser(receivedUSERId);
UserIDUpdate.setText(user.getUserid());
UserNameUpdate.setText(user.getName());
UserPasswordUpdate.setText(user.getPassword());
UserRoleUpdate.setText(user.getRole());
BtnUserRecUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUserFunction();
}
});
}
private void updateUserFunction() {
String useridupdate = UserIDUpdate.getText().toString().trim();
String usernameupdate = UserNameUpdate.getText().toString().trim();
String userpasswordupdate = UserRoleUpdate.getText().toString().trim();
String userroleupdate = UserRoleUpdate.getText().toString().trim();
if(useridupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter User ID", Toast.LENGTH_LONG).show();
}
if(usernameupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter User Name", Toast.LENGTH_LONG).show();
}
if(userpasswordupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter the password", Toast.LENGTH_LONG).show();
}
if(userroleupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter User Role", Toast.LENGTH_LONG).show();
}
//create updated person
User user = new User();
//call dbhelper update
dbHelper.updateUser(receivedUSERId, this, user);
//finally redirect back home
// NOTE you can implement an sqlite callback then redirect on success delete
goBackHome();
}
private void goBackHome() {
startActivity(new Intent(UpdateUserRec.this,UsersListActivity.class));
}
}
You are deleting data from the list that is showing data in RecyclerView. You should keep in mind Database is different entity from your list. Data base is persistent storage for data and list from where you deleting item is non persistent storage. Next time when you get data from Database the list will again fill with items that you previously deleted.
Correct method is
Delete the row from Database
Remove item from list in adapter
notifyItemRemoved(position)
You have this method in SQL class
public List<User> getAllUser() { ... }
Create one more method
public boolean deleteUser(id){
db.delete(DATABASE_TABLE, KEY_NAME + "=" + id, null)
}
On delete item call this method from your adapter with specific Id then do the same as you doing previously.
try changing your delete functionality with this and see if it works
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to Remove Item
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deletePersonRecord(listUsers.get(position).getUserid(), mContext);
listUsers.remove( position);
notifyItemRemoved(position);
mRecyclerView.removeViewAt(position);
notifyItemRangeChanged(position, listUsers.size());
notifyDataSetChanged();
dialog.cancel();
}
});
EDIT: for your new problem: about updating user
change your setPositiveButton functionality like this
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
gotupdateuserActivity(listUsers.get(position).getUserid());
// dialog.cancel();
}
});
This question has been asked before but none of the implementations helped me so far.
I'm building a to do app and I'm displaying my items in a listview, using SQLite for persistence. I'm able to dynamically add items to my listview and successfully store them in my database, but I'm not able to delete them from the screen or the table. I know the reason why. My SQLite Row ID does not match my ListView. But the other problem is that I should still be able to delete items off my screen and my table with positions that does match the SQLite Row ID (For example, my 3rd To Do in the list) but I'm not able to delete anything.
This is my method that is supposed to delete items from the database:
public boolean itemDeleteFromDatabase(long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?" + id, null) > 0;
listItems.setAdapter(adapter);
return databaseDelete;
}
And I'm calling this method from my OnItemLongClick method, passing in the ListView position as the parameter:
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
toDoItems.remove(position);
itemDeleteFromDatabase(id);
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
This is the stacktrace. The problem with this is that it only addresses 1 problem in the code:
FATAL EXCEPTION: main
Process: ca.ozbek.preworktodoapp, PID: 2105
android.database.sqlite.SQLiteException: variable number must be between ?1 and ?999 (code 1): , while compiling: DELETE FROM student WHERE todo=?0
Adding Source Code per request
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
private final int REQUEST_CODE = 10;
ArrayList <String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ListView listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
getToDos();
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
toDoItems.remove(position);
itemDeleteFromDatabase(id + 1);
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
Intent intent = new Intent(MainActivity.this, EditItemActivity.class);
intent.putExtra("item", toDoItems.get(pos));
intent.putExtra("itemPos", String.valueOf(pos));
startActivityForResult(intent, REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String item = data.getStringExtra("item");
int itemPosition = Integer.parseInt(data.getStringExtra("itemPos"));
toDoItems.add(itemPosition, item);
toDoItems.remove(itemPosition + 1);
adapter.notifyDataSetChanged();
}
}
public void addItem(View v) {
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
if (newItem.getText().length() == 0) {
Toast.makeText(this, "You need to enter a to do.", Toast.LENGTH_SHORT).show();
} else {
String item = newItem.getText().toString();
databaseHelper.insertData(item);
adapter.add(item);
newItem.setText("");
}
}
public void getToDos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex("todo"));
adapter.add(name);
adapter.notifyDataSetChanged();
cursor.moveToNext();
}
}
}
public boolean itemDeleteFromDatabase(Long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?", new String[]{Long.toString(id)}) > 0;
listItems.setAdapter(adapter);
return databaseDelete;
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final String TABLE_NAME = "student";
public static final String ID = "id";
public static final String TO_DO = "todo";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TO_DO_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ "("
+ ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TO_DO
+ " TEXT"
+ ")";
sqLiteDatabase.execSQL(CREATE_TO_DO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String todo) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor data = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
SQL is basically saying that you haven't provided an argument to match the placement ?. i.e.
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?" + id, null) > 0;
Is effectively saying DELETE FROM table WHERE TO_DO =unobtainablevale 10
10 being a made-up id for demonstration
You could change it to
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=" + id, null) > 0;
or to
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?", new String[]{Long.toString(id)}) > 0;
The latter probably being considered the better.
P.S. not tested so the odd typo might exist.
Solution 1 using a SimpleCursorAdapter as opposed to an ArrayAdpater
1) in DatabaseHelper change public static final String ID = "id"; to be public static final String ID = "_id"; (i.e add the underscore, suggest do this irrespective of method used but NEEDED for CursorAdapter)
Note! This will require the existing database to be deleted. Use Settings/Apps, select App and then clear data or uninstall app.
2) add the lines indicated with <<<<< to MainActivity (preparing to use Cursor Adapter, ps will leave the ArrayAdapter stuff generally asis but have to remove some)
ArrayList<String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
SimpleCursorAdapter altadapter; //<<<<<<<<<
Cursor itemlistcursor; //<<<<<<<<<
ListView listItems;
3) Add override for onDestroy method (not required but cleans up cursor) :-
#Override
public void onDestroy() {
super.onDestroy();
itemlistcursor.close();
}
4) Add altertantive method e.g. getItemListAsCursor to get data:-
public void getItemListAsCursor() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
itemlistcursor = database.query(TABLE_NAME,null,null,null,null,null,null);
}
Note! uses query method instead of rawQuery but equates to SELECT * FROM student;
5) Change itemDeleteFromDatabase to use ID column not the TODO column (didn't spot this before) and comment out lines as per the code below:-
public boolean itemDeleteFromDatabase(Long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
boolean databaseDelete = database.delete(TABLE_NAME, ID + "=?", new String[]{Long.toString(id)}) > 0;
//listItems.setAdapter(adapter);
return databaseDelete;
}
6) Comment out the lines as below (get rid of using ArrayAdapater) :-
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
//listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
//getToDos();
7) Change onItemLongClickListener as below
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
//toDoItems.remove(position);
itemDeleteFromDatabase(id); //<<<<<<
getItemListAsCursor(); //<<<<<<
//MainActivity.this.adapter.notifyDataSetChanged();
altadapter.swapCursor(itemlistcursor); //<<<<<<
return true;
}
});
Note! could keep notifyDatasetChanged (I just prefer swapCursor);
8) Finally add the following just after the commented out //getToDos line :-
getItemListAsCursor();
altadapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
itemlistcursor,
new String[]{ TO_DO},
new int[]{android.R.id.text1},
0);
listItems.setAdapter(altadapter);
Solution 2 using ArrayAdpater
1) Add the complimentary Array for the ID (as per the //<<<<<< line):-
ArrayList <String> toDoItems = new ArrayList<>();
ArrayList<Long> toDoItemsID = new ArrayList<>(); //<<<<<<
ArrayAdapter<String> adapter;
ListView listItems;
2) Change insertData method in DatabaseHelper to return the id by replacing the method with :-
public long insertData(String todo) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
}
3) Change getToDos method to store id into the compliementary array (//<<<<< ):-
public void getToDos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(TO_DO));
adapter.add(name);
toDoItemsID.add(cursor.getLong(cursor.getColumnIndex(ID))); //<<<<<<
adapter.notifyDataSetChanged();
cursor.moveToNext();
}
}
}
Note! I have also replaced "todo" with TO_DO
4) Change addItem method to also store id
public void addItem(View v) {
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
if (newItem.getText().length() == 0) {
Toast.makeText(this, "You need to enter a to do.", Toast.LENGTH_SHORT).show();
} else {
String item = newItem.getText().toString();
//databaseHelper.insertData(item); //OLD
toDoItemsID.add(databaseHelper.insertData(item)); //<<<<<<<
adapter.add(item);
newItem.setText("");
}
}
Note! I don't like this at all I can envisage issue with keeping toDoItemsID in sync, plus this does currently cater for a not inserted (easy to do as return from insertData should be > 0).
5) Finally the onItemLongClickListener changes :-
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
itemDeleteFromDatabase(toDoItemsID.get(position)); //<<<<<<
toDoItems.remove(position);
toDoItemsID.remove(position); //<<<<<<
//itemDeleteFromDatabase(id + 1); // REMOVE
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
I've tested the above, but may have inadvertently missed something when copying.
I'm absolute beginner.
I have a listview filled with sqlite table, I have two questions:
1- How can I sort this listview by last modified item ?
2- How can I make a button on my first page to open last modified item without going to listview !?
Here are my codes:
Its listview -
public class MainActivity extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stopService(new Intent(MainActivity.this, MyService.class));
// Locate ListView
noteListView = getListView();
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[]{ TITLE };
int[] to = new int[]{ R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.list_zekr, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(MainActivity.this, CounterActivity.class);
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
}
// Create an options menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Menu Title
menu.add("ذکر جدید")
.setOnMenuItemClickListener(this.AddNewNoteClickListener)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return super.onCreateOptionsMenu(menu);
}
// Capture menu item click
OnMenuItemClickListener AddNewNoteClickListener = new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Open AddEditNotes activity
Intent addnote = new Intent(MainActivity.this, AddEditNotes.class);
startActivity(addnote);
return false;
}
};
// GetNotes AsyncTask
public class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(MainActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes();
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
dbConnector.close();
}
}
}
its my DatabaseConnector :
public class DatabaseConnector {
// Declare Variables
private static final String DB_NAME = "database";
private static final String TABLE_NAME = "tablenotes";
private static final String TITLE = "title";
private static final String ID = "_id";
private static final String NOTE = "note";
private static final String COUNTS = "counts";
private static final String LIMITS = "limits";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase database;
private DatabaseHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseHelper(context, DB_NAME, null, DATABASE_VERSION);
}
// Open Database function
public void open() throws SQLException {
// Allow database to be in writable mode
database = dbOpenHelper.getWritableDatabase();
}
// Close Database function
public void close() {
if (database != null)
database.close();
}
// Create Database function
public void InsertNote(String title, String note, String counts, String limits) {
ContentValues newCon = new ContentValues();
newCon.put(TITLE, title);
newCon.put(NOTE, note);
newCon.put(COUNTS, counts);
newCon.put(LIMITS, limits);
open();
database.insert(TABLE_NAME, null, newCon);
close();
}
// Update Database function
public void UpdateNote(long id, String title, String note, String counts, String limits) {
ContentValues editCon = new ContentValues();
editCon.put(TITLE, title);
editCon.put(NOTE, note);
editCon.put(COUNTS, counts);
editCon.put(LIMITS, limits);
open();
database.update(TABLE_NAME, editCon, ID + "=" + id, null);
close();
}
// Delete Database function
public void DeleteNote(long id) {
open();
database.delete(TABLE_NAME, ID + "=" + id, null);
close();
}
// List all data function
public Cursor ListAllNotes() {
return database.query(TABLE_NAME, new String[]{ ID, TITLE }, null,
null, null, null, TITLE);
}
// Capture single data by ID
public Cursor GetOneNote(long id) {
return database.query(TABLE_NAME, null, ID + "=" + id, null, null,
null, null);
}
}
thanks in advance.
UPDATE !
Ok, I Created a Column in my table with name of "time"
and I can insert the time as INTEGER to it like this: 20160516100740
So now every Row of table has a time like that, NOW WHAT CAN I DO ?
Update !
Ok, I wrote this inside my list activity (MainActivity.java)
but its not working : (
public Cursor listAllSortedNotes() {
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY time DESC";
return database.rawQuery(selectQuery, null);
You need to add a field in the database which should be a date string (Sample: yyyy-MM-dd HH:mm:ss). And when you update the data, update it with current date and time. Then you can use select query to get the recent update data by using
SELECT *
FROM Table
ORDER BY datetime (dateColumn) DESC
In your case you can do something like this.
public Cursor listAllSortedNotes() {
String selectQuery = "SELECT * FROM "+ TABLE_NAME + " ORDER BY datetime(dateColumn) DESC";
return database.rawQuery(selectQuery, null);
}
I'm trying to get certain book data from my Inventory table based on the ISBN.
However, I'm getting an error: "attempt to re-open an already-closed object". The error only occurs when I click a listView object, go to a different screen, go back to this page via "finish()", and then try to click on another listView object. I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
Why does it not work if I try to getInventoryEntriesByISBN after returning to this activity from another activity via "finish()"?
The error occurs at SearchResultsScreen:
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
and by extension, occurs at InventoryAdapter:
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
SearchResultsScreen.java
// Set up search array
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
InventoryAdapter.java (Most relevant parts)
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
int publish = cursor.getInt(cursor.getColumnIndex("PUBLISH_DATE"));
String publishdate = ((Integer)publish).toString();
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
String callNumber = cursor.getString(cursor.getColumnIndex("CALL_NUMBER"));
int available = cursor.getInt(cursor.getColumnIndex("AVAILABLE_COUNT"));
String availablecount = ((Integer)available).toString();
int inventory = cursor.getInt(cursor.getColumnIndex("INVENTORY_COUNT"));
String inventorycount = ((Integer)inventory).toString();
int due = cursor.getInt(cursor.getColumnIndex("DUE_PERIOD"));
String dueperiod = ((Integer)due).toString();
int checkoutcount = cursor.getInt(cursor.getColumnIndex("COUNT"));
String count = ((Integer)checkoutcount).toString();
//combine variables into one array
searchEntry[0] = ISBN;
searchEntry[1] = title;
searchEntry[2] = author;
searchEntry[3] = publishdate;
searchEntry[4] = callNumber;
searchEntry[5] = availablecount;
searchEntry[6] = inventorycount;
searchEntry[7] = dueperiod;
searchEntry[8] = count;
cursor.close();
return searchEntry;
}
public String getTitleAndAuthorByISBN(String ISBN)
{
int entriesFound = getNumSearchEntries(ISBN);
if(entriesFound==0)
entriesFound = 1;
String searchEntry;
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
searchEntry = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
//close cursor and return
cursor.close();
return searchEntry;
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
// ============================ End Variables ===========================
public DataBaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL(CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL(InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL(StatisticsAdapter.STATISTICS_TABLE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// on upgrade drop older tables
_db.execSQL("DROP TABLE IF EXISTS " + LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + StatisticsAdapter.STATISTICS_TABLE_CREATE);
// Create a new one.
onCreate(_db);
}
}
Check Database Connection before executing query:
if (!dbHelper.db.isOpen())
dbHelper.open();
you can also use cursor.requery(); for again same query.
and in last you have to close the cursor and database also.
cursor.close();
db.close();
Edited:
I have created DBHelper class which extends SQLiteOpenHelper, this class is inner class of DatabaseHelper class and that class have following methods.
/** For OPEN database **/
public synchronized DatabaseHelper open() throws SQLiteException {
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
/** For CLOSE database **/
public void close() {
dbHelper.close();
}
If you have still doubt then feel free to ping me. Thank you.
The error only occurs when I click an item, go to a different screen, go back to this page via "finish()", and then try to click on another listView object.
I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
The correct SearchResultsScreen is below:
SearchResultsScreen.java
// Set up search array
final String Entries[][] = new String[isbn.length][9];
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
Entries[i] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[i]);
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = Entries[position];
This is your problem
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
cursor.close();
Change to
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
{
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
}
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
Add SQLiteDatabase db = this.getWritableDatabase(); in this code before executing the raw Query
I wonder if someone could show me the error of my ways--I've been struggling with this issue for two days, and realize it must be a fundamental error of initializing variables, but...that reflects the level of my java knowledge.
I'm getting a database result on a delimited string wherein each of the segments has "null" appended to it. It seems that no matter how I change the initialization...well, two days!
I'm declaring the following in the class heading area:
private String strListContent;
private SQLiteDatabase database;
private DatabaseHelper helper2 = new DatabaseHelper(this);
private static final String fields[] = { "_id", "listTitle", "listType",
"listContent", "dateCreated", "dateModified" };
private ArrayList<String> textArray = new ArrayList<String>();
private ArrayList<Integer> imageArray = new ArrayList<Integer>();
Then concatenating my items in
final ImageButton addItem = (ImageButton) findViewById(R.id.btnToAddItem);
addItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemEdit = (EditText) findViewById(R.id.editTextItem);
if (itemEdit.getText().toString().equals("")) {
showToastMessage("Please enter an item to add...");
} else {
String newListItem = itemEdit.getText().toString();
strListContent += newListItem + "|~|";
...
}}}
I'm using the following bare-bones SQLiteOpenHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, "Cursor", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS list_data ("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, listTitle TEXT, listType TEXT, listContent TEXT, dateCreated TEXT, dateModified TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Steps to upgrade the database for the new version ...
}
}
To insert the values as so:
ImageButton saveAndBack = (ImageButton) findViewById(R.id.btnSaveBack);
saveAndBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String title = null;
String listContent = null;
Calendar javaCalendar = null;
title = titleEdit.getText().toString();
title = (title=="" || title==null)?"Untitled List":title;
strListContent = (strListContent=="" || strListContent==null)?"No Items|~|":strListContent;
listContent = strListContent;
String type = "R"; //"Regular List"
javaCalendar = Calendar.getInstance();
String currentDate = javaCalendar.get(Calendar.MONTH) + "/" + (javaCalendar.get(Calendar.DATE) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
database = helper2.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("listTitle", title);
values.put("listType", type);
values.put("listContent", listContent);
values.put("dateCreated", currentDate);
values.put("dateModified", currentDate);
database.insert("list_data", null, values);
Intent i = new Intent(RegularList.this, ActivityMain.class);
startActivity(i);
}
});
}
//
//End of OnCreate(){}
//
Then, when I retrieve from another activity:
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("list_data", fields, null, null, null,
null, null);
Integer tindex = data.getColumnIndex("listTitle");
Integer iindex = data.getColumnIndex("listType");
Integer cindex = data.getColumnIndex("listContent");
itemCount = 0;
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
showToastMessage(data.getString(cindex));
titleArrayList.add(data.getString(tindex));
if (data.getString(iindex) == "R") {
imageArrayList.add(R.drawable.listview_regular);
} else if (data.getString(iindex) == "L") {
imageArrayList.add(R.drawable.listview_location);
} else {
imageArrayList.add(R.drawable.listview_regular);
}
itemCount++;
}
data.close();
...
I can see in the toast message that each item from the delimited string has "null" appended to the front of it...the other values are fine. I hope this hasn't been too verbose, but...any recommendations? Thanks!
To me it looks like you may have simply not initialised the String strListContent before you first append to it with:
strListContent += newListItem + "|~|";
When you do that, you'll get a "null" prefixed in front of the value you are trying to append, just as you observe.
Perhaps you can just initialise in the declaration:
private String strListContent = "";